Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 views
in Technique[技术] by (71.8m points)

python: how to sort lists alphabetically with respect to capitalized letters

I'm trying to sort a list alphabetically, where capital letters should come before lower case letters.

l = ['a', 'b', 'B', 'A']

sorted(l) should result in ['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']
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create a tuple as your key instead:

>>> sorted(lst, key=lambda L: (L.lower(), L))
['A', 'a', 'B', 'b']

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...