问题:不区分大小写的列表排序,而不降低结果大小?
我有一个这样的字符串列表:
['Aden', 'abel']
我要对项目排序,不区分大小写。所以我想得到:
['abel', 'Aden']
但与sorted()
或相反list.sort()
,因为大写字母先于小写字母。
我如何忽略这种情况?我已经看到了涉及降低所有列表项的解决方案,但是我不想更改列表项的大小写。
I have a list of strings like this:
['Aden', 'abel']
I want to sort the items, case-insensitive.
So I want to get:
['abel', 'Aden']
But I get the opposite with sorted()
or list.sort()
, because uppercase appears before lowercase.
How can I ignore the case? I’ve seen solutions which involves lowercasing all list items, but I don’t want to change the case of the list items.
回答 0
在Python 3.3+中,有str.casefold
一种专为无条件匹配而设计的方法:
sorted_list = sorted(unsorted_list, key=str.casefold)
在Python 2中使用lower()
:
sorted_list = sorted(unsorted_list, key=lambda s: s.lower())
它适用于普通字符串和unicode字符串,因为它们都有lower
方法。
在Python 2中,它可以将普通字符串和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']
In Python 3.3+ there is the str.casefold
method that’s specifically designed for caseless matching:
sorted_list = sorted(unsorted_list, key=str.casefold)
In Python 2 use lower()
:
sorted_list = sorted(unsorted_list, key=lambda s: s.lower())
It works for both normal and unicode strings, since they both have a lower
method.
In Python 2 it works for a mix of normal and unicode strings, since values of the two types can be compared with each other. Python 3 doesn’t work like that, though: you can’t compare a byte string and a unicode string, so in Python 3 you should do the sane thing and only sort lists of one type of string.
>>> lst = ['Aden', u'abe1']
>>> sorted(lst)
['Aden', u'abe1']
>>> sorted(lst, key=lambda s: s.lower())
[u'abe1', 'Aden']
回答 1
>>> x = ['Aden', 'abel']
>>> sorted(x, key=str.lower) # Or unicode.lower if all items are unicode
['abel', 'Aden']
在Python 3中str
是unicode,但在Python 2中,您可以使用这种更通用的方法,该方法对str
和都适用unicode
:
>>> sorted(x, key=lambda s: s.lower())
['abel', 'Aden']
>>> x = ['Aden', 'abel']
>>> sorted(x, key=str.lower) # Or unicode.lower if all items are unicode
['abel', 'Aden']
In Python 3 str
is unicode but in Python 2 you can use this more general approach which works for both str
and unicode
:
>>> sorted(x, key=lambda s: s.lower())
['abel', 'Aden']
回答 2
您也可以尝试使用此方法对列表进行就地排序:
>>> x = ['Aden', 'abel']
>>> x.sort(key=lambda y: y.lower())
>>> x
['abel', 'Aden']
You can also try this to sort the list in-place:
>>> x = ['Aden', 'abel']
>>> x.sort(key=lambda y: y.lower())
>>> x
['abel', 'Aden']
回答 3
这在Python 3中有效,并且不涉及小写结果(!)。
values.sort(key=str.lower)
This works in Python 3 and does not involves lowercasing the result (!).
values.sort(key=str.lower)
回答 4
在python3中,您可以使用
list1.sort(key=lambda x: x.lower()) #Case In-sensitive
list1.sort() #Case Sensitive
In python3 you can use
list1.sort(key=lambda x: x.lower()) #Case In-sensitive
list1.sort() #Case Sensitive
回答 5
我是通过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)
I did it this way for 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]
Then you just can call this function:
sortCaseIns(yourListToSort)
回答 6
不区分大小写的排序,在Python 2 OR 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
Case-insensitive sort, sorting the string in place, in Python 2 OR 3 (tested in Python 2.7.17 and 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']
The key is key=str.lower
. Here’s what those commands look like with just the commands, for easy copy-pasting so you can test them:
x = ["aa", "A", "bb", "B", "cc", "C"]
x.sort()
x
x.sort(key=str.lower)
x
Note that if your strings are unicode strings, however (like u'some string'
), then in Python 2 only (NOT in Python 3 in this case) the above x.sort(key=str.lower)
command will fail and output the following error:
TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode'
If you get this error, then either upgrade to Python 3 where they handle unicode sorting, or convert your unicode strings to ASCII strings first, using a list comprehension, like this:
# 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:
- https://docs.python.org/3/library/stdtypes.html#list.sort
- Convert a Unicode string to a string in Python (containing extra symbols)
- https://www.programiz.com/python-programming/list-comprehension
回答 7
试试这个
def cSort(inlist, minisort=True):
sortlist = []
newlist = []
sortdict = {}
for entry in inlist:
try:
lentry = entry.lower()
except AttributeError:
sortlist.append(lentry)
else:
try:
sortdict[lentry].append(entry)
except KeyError:
sortdict[lentry] = [entry]
sortlist.append(lentry)
sortlist.sort()
for entry in sortlist:
try:
thislist = sortdict[entry]
if minisort: thislist.sort()
newlist = newlist + thislist
except KeyError:
newlist.append(entry)
return newlist
lst = ['Aden', 'abel']
print cSort(lst)
输出量
['abel', 'Aden']
Try this
def cSort(inlist, minisort=True):
sortlist = []
newlist = []
sortdict = {}
for entry in inlist:
try:
lentry = entry.lower()
except AttributeError:
sortlist.append(lentry)
else:
try:
sortdict[lentry].append(entry)
except KeyError:
sortdict[lentry] = [entry]
sortlist.append(lentry)
sortlist.sort()
for entry in sortlist:
try:
thislist = sortdict[entry]
if minisort: thislist.sort()
newlist = newlist + thislist
except KeyError:
newlist.append(entry)
return newlist
lst = ['Aden', 'abel']
print cSort(lst)
Output
['abel', 'Aden']