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
578 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 Answer

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.


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

...