Hướng dẫn python list sort case insensitive - danh sách python phân biệt chữ hoa chữ thường

Sắp xếp không phân biệt chữ hoa chữ thường, sắp xếp chuỗi tại chỗ, trong Python 2 hoặc 3 (được thử nghiệm trong Python 2.7.17 và Python 3.6.9):

>>> x = ["aa", "A", "bb", "B", "cc", "C"]
>>> x.sort()
>>> x
['A', 'B', 'C', 'aa', 'bb', 'cc']
>>> x.sort(key=str.lower)           # <===== there it is!
>>> x
['A', 'aa', 'B', 'bb', 'C', 'cc']

Chìa khóa là

x = ["aa", "A", "bb", "B", "cc", "C"]
x.sort()
x
x.sort(key=str.lower)
x
5. Dưới đây là những lệnh đó trông như thế nào chỉ với các lệnh, để dễ dàng sao chép để bạn có thể kiểm tra chúng:

x = ["aa", "A", "bb", "B", "cc", "C"]
x.sort()
x
x.sort(key=str.lower)
x

Lưu ý rằng nếu chuỗi của bạn là chuỗi unicode, tuy nhiên (như

x = ["aa", "A", "bb", "B", "cc", "C"]
x.sort()
x
x.sort(key=str.lower)
x
6), thì chỉ trong Python 2 (không phải trong Python 3 trong trường hợp này), lệnh
x = ["aa", "A", "bb", "B", "cc", "C"]
x.sort()
x
x.sort(key=str.lower)
x
7 trên sẽ không thành công và xuất ra lỗi sau:

TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'

Nếu bạn gặp lỗi này, thì hãy nâng cấp lên Python 3, nơi chúng xử lý việc sắp xếp Unicode hoặc chuyển đổi chuỗi Unicode của bạn thành chuỗi ASCII trước, sử dụng khả năng hiểu danh sách, như thế này:

# for Python2, ensure all elements are ASCII (NOT unicode) strings first
x = [str(element) for element in x]  
# for Python2, this sort will only work on ASCII (NOT unicode) strings
x.sort(key=str.lower)

References:

  1. https://docs.python.org/3/library/stdtypes.html#list.sort
  2. Chuyển đổi chuỗi Unicode thành chuỗi trong Python (chứa các ký hiệu bổ sung)
  3. https://www.programiz.com/python-programming/list-comprehension

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Cải thiện bài viết

    Lưu bài viết

    Đọc
    Method #1: Using casefold() 
     

    Bàn luận

    Đưa ra một danh sách các chuỗi, một nhiệm vụ là sắp xếp các chuỗi theo cách không nhạy cảm. Đưa ra dưới đây là một vài phương pháp để giải quyết nhiệm vụ.

    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    9
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    0
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    2
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    4
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    5

    Python3

    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    0
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    1
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    2
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    4
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    5

    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    8
    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    9
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    0
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    1
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    3__22222525222227272828

    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    0
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    1
    # Sort the list of numbers
    L = [42, 99, 1, 12]
    L.sort()
    print(L)
    # Prints [1, 12, 42, 99]
    5
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    4
    # Sort the list of numbers
    L = [42, 99, 1, 12]
    L.sort()
    print(L)
    # Prints [1, 12, 42, 99]
    8

    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    6
    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    9
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    8
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    9
     
    Case-sensitive sorted list [‘Alind’, ‘GeeksForGeeks’, ‘Munich’, ‘SIngh’, ‘akshat’, ‘garg’, ‘manjeet’] 
    Case-insensitive sorted list [‘akshat’, ‘Alind’, ‘garg’, ‘GeeksForGeeks’, ‘manjeet’, ‘Munich’, ‘SIngh’] 
     

    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    6
    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    9
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    8
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    9
    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    9
    # Sort the list of numbers
    L = [42, 99, 1, 12]
    L.sort()
    print(L)
    # Prints [1, 12, 42, 99]
    1
    # Sort the list of numbers
    L = [42, 99, 1, 12]
    L.sort()
    print(L)
    # Prints [1, 12, 42, 99]
    2
    Method #2: Using lower() 
     

    Python3

    Đưa ra một danh sách các chuỗi, một nhiệm vụ là sắp xếp các chuỗi theo cách không nhạy cảm. Đưa ra dưới đây là một vài phương pháp để giải quyết nhiệm vụ.

    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    9
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    0
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    2
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    4
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    5

    Python3

    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    0
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    1
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    2
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    4
    L = ['red', 'green', 'blue', 'orange']
    L.sort(key=len)
    print(L)
    # Prints ['red', 'blue', 'green', 'orange']
    3

    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    8
    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    9
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    0
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    1
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    3__22222525222227272828

    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    0
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    1
    # Sort the list of numbers
    L = [42, 99, 1, 12]
    L.sort()
    print(L)
    # Prints [1, 12, 42, 99]
    5
    TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
    
    2
    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']
    4
    L = ['red', 'green', 'blue', 'orange']
    L.sort(key=len)
    print(L)
    # Prints ['red', 'blue', 'green', 'orange']
    3

    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    6
    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    9
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    8
    # for Python2, ensure all elements are ASCII (NOT unicode) strings first
    x = [str(element) for element in x]  
    # for Python2, this sort will only work on ASCII (NOT unicode) strings
    x.sort(key=str.lower)
    
    9
     
    Case-sensitive sorted list [‘Alind’, ‘GeeksForGeeks’, ‘Munich’, ‘SIngh’, ‘akshat’, ‘garg’, ‘manjeet’] 
    Case-insensitive sorted list [‘akshat’, ‘Alind’, ‘garg’, ‘GeeksForGeeks’, ‘manjeet’, ‘Munich’, ‘SIngh’] 
     


    Sắp xếp các mục của danh sách

    Cách sử dụng

    Sử dụng phương thức

    # Sort a list of tuples based on the age of students
    def myFunc(e):
      return e[1]	# return age
    
    L = [('Bob', 30),
         ('Sam', 35),
         ('Max', 25)]
    L.sort(key=myFunc)
    print(L)
    # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
    4 để sắp xếp các mục của danh sách.

    Bạn có thể tùy chọn chỉ định các tham số để sắp xếp tùy chỉnh như sắp xếp đơn hàng và sắp xếp tiêu chí.

    Cú pháp

    list.sort(key,reverse)sort(key,reverse)

    Tham số Phương thức Danh sách Python () tham số
    Tham sốTình trạngSự mô tả
    Chìa khóaKhông bắt buộcMột hàm để chỉ định giá trị tiêu chí sắp xếp.default là không có.
    Default value is None.
    đảo ngượcKhông bắt buộcMột hàm để chỉ định giá trị tiêu chí sắp xếp.default là không có.
    Default value is False.

    đảo ngượckeyword arguments.

    Giải quyết nó thành các loại thực sự danh sách theo thứ tự ngược lại.default giá trị là sai.

    # Sort the list of strings
    L = ['red', 'green', 'blue', 'orange']
    L.sort()
    print(L)
    # Prints ['blue', 'green', 'orange', 'red']

    # Sort the list of numbers
    L = [42, 99, 1, 12]
    L.sort()
    print(L)
    # Prints [1, 12, 42, 99]

    Xin lưu ý rằng cả hai đối số phải được chỉ định là đối số từ khóa.

    L = ['red', 'blue', 1, 12, 'orange',42, 'green', 99]
    L.sort()
    # Triggers TypeError: '<' not supported between instances of 'int' and 'str'

    Phương pháp # Sort a list of tuples based on the age of students def myFunc(e): return e[1] # return age L = [('Bob', 30), ('Sam', 35), ('Max', 25)] L.sort(key=myFunc) print(L) # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]4 Sắp xếp danh sách các chuỗi theo thứ tự bảng chữ cái và danh sách các số bằng số.

    Tuy nhiên, bạn không thể sắp xếp các danh sách có cả số và chuỗi trong đó, vì Python không biết cách so sánh các giá trị này.reverse to TRUE.

    L = ['red', 'green', 'blue', 'orange']
    L.sort(reverse=True)
    print(L)
    # Prints ['red', 'orange', 'green', 'blue']

    Sắp xếp danh sách theo thứ tự ngược lại

    Bạn cũng có thể sắp xếp danh sách theo thứ tự ngược lại bằng cách đặt ngược lại thành true.key parameter for more complex custom sorting. A key parameter specifies a function to be executed on each list item before making comparisons.

    Ví dụ, với một danh sách các chuỗi, chỉ định

    # Sort a list of tuples based on the age of students
    def myFunc(e):
      return e[1]	# return age
    
    L = [('Bob', 30),
         ('Sam', 35),
         ('Max', 25)]
    L.sort(key=myFunc)
    print(L)
    # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
    6 (hàm Len () tích hợp) sắp xếp các chuỗi theo chiều dài, từ ngắn nhất đến dài nhất.

    L = ['red', 'green', 'blue', 'orange']
    L.sort(key=len)
    print(L)
    # Prints ['red', 'blue', 'green', 'orange']

    Một hàm được sử dụng làm khóa phải lấy một giá trị duy nhất và trả về giá trị đơn.

    Sắp xếp với chức năng tùy chỉnh

    Bạn cũng có thể vượt qua chức năng tùy chỉnh của riêng mình

    # Sort a list of tuples based on the age of students
    def myFunc(e):
      return e[1]	# return age
    
    L = [('Bob', 30),
         ('Sam', 35),
         ('Max', 25)]
    L.sort(key=myFunc)
    print(L)
    # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
    7 làm chức năng chính.key function.

    # Sort a list of tuples based on the age of students
    def myFunc(e):
      return e[1]	# return age
    
    L = [('Bob', 30),
         ('Sam', 35),
         ('Max', 25)]
    L.sort(key=myFunc)
    print(L)
    # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]

    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    0

    Sắp xếp không nhạy cảm trường hợp

    Theo mặc định, phương pháp

    # Sort a list of tuples based on the age of students
    def myFunc(e):
      return e[1]	# return age
    
    L = [('Bob', 30),
         ('Sam', 35),
         ('Max', 25)]
    L.sort(key=myFunc)
    print(L)
    # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
    4 sắp xếp danh sách theo thứ tự asciibetical chứ không phải là thứ tự bảng chữ cái thực tế. Điều này có nghĩa là các chữ cái chữ hoa đến trước các chữ cái viết thường.ASCIIbetical order rather than actual alphabetical order. This means uppercase letters come before lowercase letters.

    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    1

    Nếu bạn muốn sắp xếp các giá trị theo thứ tự bảng chữ cái thông thường, hãy đặt khóa thành str.lowerkey to str.lower

    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    2

    Điều này khiến chức năng

    # Sort a list of tuples based on the age of students
    def myFunc(e):
      return e[1]	# return age
    
    L = [('Bob', 30),
         ('Sam', 35),
         ('Max', 25)]
    L.sort(key=myFunc)
    print(L)
    # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
    4 xử lý tất cả các mục danh sách như thể chúng là chữ thường mà không thực sự thay đổi các giá trị trong danh sách.

    Sắp xếp () vs Sắp xếp ()

    Phương thức

    # Sort a list of tuples based on the age of students
    def myFunc(e):
      return e[1]	# return age
    
    L = [('Bob', 30),
         ('Sam', 35),
         ('Max', 25)]
    L.sort(key=myFunc)
    print(L)
    # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
    4 không trả lại bất cứ điều gì, nó sửa đổi danh sách ban đầu (nghĩa là các loại tại chỗ). Nếu bạn không muốn sửa đổi danh sách ban đầu, hãy sử dụng hàm Sắp xếp (). Nó trả về một bản sao sắp xếp của danh sách.

    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    3

    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    4

    Một điểm khác biệt khác là phương thức

    # Sort a list of tuples based on the age of students
    def myFunc(e):
      return e[1]	# return age
    
    L = [('Bob', 30),
         ('Sam', 35),
         ('Max', 25)]
    L.sort(key=myFunc)
    print(L)
    # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
    4 chỉ được xác định cho danh sách. Ngược lại, hàm
    x = ["aa", "A", "bb", "B", "cc", "C"]
    x.sort()
    x
    x.sort(key=str.lower)
    x
    
    02 chấp nhận bất kỳ sự khác biệt như tuple, từ điển, v.v. Ngoài ra, phương pháp
    # Sort a list of tuples based on the age of students
    def myFunc(e):
      return e[1]	# return age
    
    L = [('Bob', 30),
         ('Sam', 35),
         ('Max', 25)]
    L.sort(key=myFunc)
    print(L)
    # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
    4 không cần phải tạo một danh sách mới, do đó, nó nhanh hơn giữa hai phương pháp.

    Nên sắp xếp là trường hợp

    Sắp xếp trên cơ sở các giá trị ASCII phân biệt các chữ cái viết hoa với các chữ cái viết thường và dẫn đến một thứ tự nhạy cảm trường hợp.Mặc dù các kết quả trong cột thứ tự tăng dần lúc đầu có thể xuất hiện hơi khó lường, nhưng chúng không phải vậy.. Although the results in the Ascending order column might at first appear somewhat unpredictable, they are not.

    Key Str thấp hơn Python là gì?

    Phương thức Python chuỗi thấp hơn () chuyển đổi tất cả các ký tự chữ hoa trong một chuỗi thành các ký tự chữ thường và trả về nó.converts all uppercase characters in a string into lowercase characters and returns it.

    Ignorecase trong Python là gì?

    IGNORECASE: Cờ này cho phép khớp không nhạy cảm với biểu thức thông thường với chuỗi đã cho, tức là các biểu thức như [A-Z] cũng sẽ khớp với các chữ cái viết thường.This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too.

    Sự khác biệt giữa sắp xếp và sắp xếp trong Python là gì?

    Sự khác biệt chính giữa sắp xếp và được sắp xếp trong Python là hàm sắp xếp không trả về không có gì và thay đổi chuỗi gốc, trong khi hàm Sắp xếp () tạo ra một loại chuỗi mới chứa phiên bản được sắp xếp của chuỗi đã cho.sort function returns nothing and makes changes to the original sequence, while the sorted () function creates a new sequence type containing a sorted version of the given sequence.