Reputation: 4099
I have followed this link and tried various probabilities to get the desired output
sorted(['aa', 'bb', '_dd', 'BB', 'AA'])
['AA', 'BB', '_dd', 'aa', 'bb']
sorted(['aa', 'bb', '_dd', 'BB', 'AA'], reverse=True)
['bb', 'aa', '_dd', 'BB', 'AA']
sorted(['aa', 'bb', '_dd', 'BB', 'AA'], key=str.lower)
['_dd', 'aa', 'AA', 'bb', 'BB']
sorted(['aa', 'bb', '_dd', 'BB', 'AA'], reverse=True, key=str.lower)
['bb', 'BB', 'aa', 'AA', '_dd']
sorted(sorted(['aa', 'bb', '_dd', 'BB', 'AA'], reverse=False), key=str.lower)
['_dd', 'AA', 'aa', 'BB', 'bb']
sorted(sorted(['aa', 'bb', '_dd', 'BB', 'AA'], reverse=True), key=str.lower)
['_dd', 'aa', 'AA', 'bb', 'BB']
sorted(sorted(['aa', 'bb', '_dd', 'BB', 'AA'], reverse=True), key=lambda x: (x.lower(), x.swapcase()))
['_dd', 'aa', 'AA', 'bb', 'BB']
sorted(['aa', 'bb', '_dd', 'BB', 'AA'], key=str.istitle)
['aa', 'bb', '_dd', 'BB', 'AA']
sorted(['aa', 'bb', '_dd', 'BB', 'AA'], reverse=True, key=str.istitle)
['aa', 'bb', '_dd', 'BB', 'AA']
sorted(['aa', 'bb', '_dd', 'BB', 'AA'], reverse=False, key=str.istitle)
['aa', 'bb', '_dd', 'BB', 'AA']
sorted(sorted(['aa', 'bb', '_dd', 'BB', 'AA']), key=str.istitle)
['AA', 'BB', '_dd', 'aa', 'bb']
sorted(sorted(['aa', 'bb', '_dd', 'BB', 'AA'], reverse=True), key=str.istitle)
['bb', 'aa', '_dd', 'BB', 'AA']
But I need the output to be in this order
['_dd', 'aa', 'bb', 'AA', 'BB']
Upvotes: 1
Views: 99
Reputation: 10727
Try this:
sorted(['aa', 'bb', '_dd', 'BB', 'AA'], key=lambda s: (s.upper() == s, s))
Tuples are sorted by its first item before the second, and bools are sorted as False before true, so the s.upper() == s
will sort all non-uppercase ones before the others.
Note that, if your purpose is language-oriented sorting, you should probably look into using key=functools.cmp_to_key(locale.strcoll)
or similar instead.
Upvotes: 2