How to sort a list of strings?

后端 未结 11 787
孤独总比滥情好
孤独总比滥情好 2020-11-22 11:22

What is the best way of creating an alphabetically sorted list in Python?

相关标签:
11条回答
  • 2020-11-22 11:31

    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)

    0 讨论(0)
  • 2020-11-22 11:33

    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.)

    0 讨论(0)
  • 2020-11-22 11:36
    list.sort()
    

    It really is that simple :)

    0 讨论(0)
  • 2020-11-22 11:36

    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.

    0 讨论(0)
  • 2020-11-22 11:38

    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.

    0 讨论(0)
  • 2020-11-22 11:51

    Please use sorted() function in Python3

    items = ["love", "like", "play", "cool", "my"]
    sorted(items2)
    
    0 讨论(0)
提交回复
热议问题