Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Sort list of strings by integer suffix

I have a list of strings:

[song_1, song_3, song_15, song_16, song_4, song_8]

I would like to sort them by the # at the end, unfortunately since the lower numbers aren't "08" and are "8", they are treated as larger than 15 in lexicographical order.

I know I have to pass a key to the sort function, I saw this somewhere on this site to sort decimal numbers that are strings:

sorted(the_list, key=lambda a:map(int,a.split('.'))

But that was for "1.2, 2.5, 2.3" but I don't have that case. I thought of replacing '.' with '_' but from what I understand it converts both sides to ints, which will fail since the left side of the _ is a string.

EDIT: I forgot to mention that all the prefixes are the same (song in this example)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're close.

sorted(the_list, key = lambda x: int(x.split("_")[1]))

should do it. This splits on the underscore, takes the second part (i.e. the one after the first underscore), and converts it to integer to use as a key.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...