How to sort a list of strings?

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

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

11条回答
  •  眼角桃花
    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.)

提交回复
热议问题