简体   繁体   English

Python按元组中的值的长度对List进行排序

[英]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: 如果我按元素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的方式?

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; 另外,不要使用list作为变量名; it's already taken by a built-in function. 它已经被内置函数占用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM