Sort list of strings ignoring upper/lower case

后端 未结 3 959
青春惊慌失措
青春惊慌失措 2020-12-05 02:38

I have a list which contains strings representing animal names. I need to sort the list. If I use sorted(list), it will give the list output with uppercase stri

3条回答
  •  我在风中等你
    2020-12-05 03:22

    I need to add yet another answer, since both the accepted answer and the newer versions lack one important thing:

    The here proposed case-insensitive sorting is not stable in the ordering of "equal" keys!

    That means: When you have a mixture of mixed case strings that you want to sort, you get a correctly sorted list, but it is undefined whether "AbC" comes before "aBc" or after. This may even vary between runs of the same program.

    In order to always have the same output with a stable default ordering of strings, I use the following function:

    sorted(var, key=lambda v: (v.casefold(), v))
    

    This way, the original key is always appended as a fallback ordering when the casefold version does not supply a difference to sort on.

提交回复
热议问题