What is the best way of creating an alphabetically sorted list in Python?
It is simple: https://trinket.io/library/trinkets/5db81676e4
scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'
scores = scores.split(',') for x in sorted(scores): print(x)
Old question, but if you want to do locale-aware sorting without setting locale.LC_ALL
you can do so by using the PyICU library as suggested by this answer:
import icu # PyICU
def sorted_strings(strings, locale=None):
if locale is None:
return sorted(strings)
collator = icu.Collator.createInstance(icu.Locale(locale))
return sorted(strings, key=collator.getSortKey)
Then call with e.g.:
new_list = sorted_strings(list_of_strings, "de_DE.utf8")
This worked for me without installing any locales or changing other system settings.
(This was already suggested in a comment above, but I wanted to give it more prominence, because I missed it myself at first.)
list.sort()
It really is that simple :)
The proper way to sort strings is:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']
# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']
The previous example of mylist.sort(key=lambda x: x.lower())
will work fine for ASCII-only contexts.
It is also worth noting the sorted() function:
for x in sorted(list):
print x
This returns a new, sorted version of a list without changing the original list.
Please use sorted() function in Python3
items = ["love", "like", "play", "cool", "my"]
sorted(items2)