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:
如果我按元素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,
我可以使用lambda和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?
但使用键和/或项目符号是否有更优雅或pythonic的方式?
1 个解决方案
#1
12
Well you can make the lambda simpler:
那么你可以使lambda更简单:
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.
另外,不要使用list作为变量名;它已经被内置函数占用了。
#1
12
Well you can make the lambda simpler:
那么你可以使lambda更简单:
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.
另外,不要使用list作为变量名;它已经被内置函数占用了。