我有一个字符串列表,像这样:

['Aden', 'abel']

我想对项目进行排序,不区分大小写。 我想要得到:

['abel', 'Aden']

但是我用sorted()或list.sort()得到相反的结果,因为大写字母出现在小写字母之前。

我怎么能无视这个案子呢?我看到的解决方案包括小写所有列表项,但我不想改变列表项的大小写。


当前回答

在python3中可以使用

list1.sort(key=lambda x: x.lower()) #Case In-sensitive             
list1.sort() #Case Sensitive

其他回答

你也可以这样对列表进行排序:

>>> x = ['Aden', 'abel']
>>> x.sort(key=lambda y: y.lower())
>>> x
['abel', 'Aden']

在python3中可以使用

list1.sort(key=lambda x: x.lower()) #Case In-sensitive             
list1.sort() #Case Sensitive

我在Python 3.3中是这样做的:

 def sortCaseIns(lst):
    lst2 = [[x for x in range(0, 2)] for y in range(0, len(lst))]
    for i in range(0, len(lst)):
        lst2[i][0] = lst[i].lower()
        lst2[i][1] = lst[i]
    lst2.sort()
    for i in range(0, len(lst)):
        lst[i] = lst2[i][1]

然后你可以调用这个函数:

sortCaseIns(yourListToSort)

不区分大小写的排序,在Python 2或3中对字符串进行排序(在Python 2.7.17和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']

键是key=str.lower。下面是这些命令的样子,为了方便复制粘贴,你可以测试它们:

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

注意,如果你的字符串是unicode字符串(比如u'some string'),那么只在Python 2中(在这种情况下不是在Python 3中)上述x.sort(key=str.lower)命令将失败并输出以下错误:

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

如果你得到这个错误,那么要么升级到Python 3,在那里他们处理unicode排序,要么先将你的unicode字符串转换为ASCII字符串,使用一个列表理解,像这样:

# 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)

引用:

https://docs.python.org/3/library/stdtypes.html#list.sort 将Unicode字符串转换为Python中的字符串(包含额外符号) https://www.programiz.com/python-programming/list-comprehension

在Python 3.3+中,有str.casefold方法是专门为无大小写匹配而设计的:

sorted_list = sorted(unsorted_list, key=str.casefold)

在python2中使用lower():

sorted_list = sorted(unsorted_list, key=lambda s: s.lower())

它适用于普通字符串和unicode字符串,因为它们都有一个较低的方法。

在python2中,它适用于普通字符串和unicode字符串的混合,因为这两种类型的值可以相互比较。不过Python 3并不是这样工作的:你不能比较字节字符串和unicode字符串,所以在Python 3中你应该做理智的事情,只对一种类型的字符串的列表进行排序。

>>> lst = ['Aden', u'abe1']
>>> sorted(lst)
['Aden', u'abe1']
>>> sorted(lst, key=lambda s: s.lower())
[u'abe1', 'Aden']