问题
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.
回答1:
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']
回答2:
>>> 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']
回答3:
You can also try this:
>>> x = ['Aden', 'abel']
>>> x.sort(key=lambda y: y.lower())
>>> x
['abel', 'Aden']
回答4:
In python3 you can use
list1.sort(key=lambda x: x.lower()) #Case In-sensitive
list1.sort() #Case Sensitive
回答5:
This works in Python 3 and does not involves lowercasing the result (!).
values.sort(key=str.lower)
回答6:
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)
回答7:
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']
来源:https://stackoverflow.com/questions/10269701/case-insensitive-list-sorting-without-lowercasing-the-result