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
586 views
in Technique[技术] by (71.8m points)

sorting - Python sort a List by length of value in tuple

I am having difficulty sorting a list of tuples. I would like to sort by the length of a string in the list.

For example:

l = [(99,'bbc', 121),(33,'abcd', 231),(44,'zb', 148), (23,'abcde',221)]

if I sort by element 1:

l.sort(key=itemgetter(1), reverse=True)

This will sort on the alphabetical ranking of the strings, not the length. I would prefer to sort in-place and reverse sort, with longest string first.

I can use a lambda and cmp,

l.sort(lambda x,y: cmp(len(x[1]), len(y[1])), reverse=True)

but is there a more elegant, or pythonic way using key and/or itemgetter?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Well you can make the lambda simpler:

l.sort(key=lambda t: len(t[1]), reverse=True)

Also, don't use list as a variable name; it's already taken by a built-in function.


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

...