不区分大小写的列表排序,而不降低结果的大小? [英] case-insensitive list sorting, without lowercasing the result?
问题描述
我有一个这样的字符串列表:
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']
但是与sorted()
或list.sort()
相反,因为大写字母出现在小写字母之前.
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.
推荐答案
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)
在Python 2中使用lower()
:
In Python 2 use lower()
:
sorted_list = sorted(unsorted_list, key=lambda s: s.lower())
它适用于普通字符串和unicode字符串,因为它们都具有lower
方法.
It works for both normal and unicode strings, since they both have a lower
method.
在Python 2中,它可以将普通字符串和unicode字符串混合使用,因为这两种类型的值可以相互比较.但是,Python 3不能那样工作:您不能比较字节字符串和unicode字符串,因此在Python 3中,您应该做明智的事情,并且只能对一种类型的字符串列表进行排序.
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']
这篇关于不区分大小写的列表排序,而不降低结果的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!