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?
解决方案
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.