How to sort a list of strings?

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

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

11条回答
  •  悲哀的现实
    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.

提交回复
热议问题