本文介绍了python:如何针对大写字母按字母顺序对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试按字母顺序对列表进行排序,其中大写字母应位于小写字母之前.
I'm trying to sort a list alphabetically, where capital letters should come before lower case letters.
l = ['a', 'b', 'B', 'A']
sorted(l)
应该导致['A','a','B','b']
我尝试了这两种形式,但无济于事;
I've tried these two forms, but to no avail;
>>> sorted(l, key=lambda s: s.lower())
['a', 'A', 'b', 'B']
>>> sorted(l, key=str.lower)
['a', 'A', 'b', 'B']
推荐答案
相反,创建一个元组作为键:
Create a tuple as your key instead:
>>> sorted(lst, key=lambda L: (L.lower(), L))
['A', 'a', 'B', 'b']
这意味着小写字母的排序顺序不会改变('a', 'a')
,但意味着大写字母的第一个键将其与小写字母等效,然后在其前面进行排序:例如('a', 'A')
< ('a', 'a')
This means the sort order for lower-case doesn't change ('a', 'a')
but means the first key for upper case puts it level with the lower-case equivalent, then sorts before it: eg ('a', 'A')
< ('a', 'a')
这篇关于python:如何针对大写字母按字母顺序对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!