Python按元组中值的长度对列表进行排序 [英] Python sort a List by length of value in tuple
本文介绍了Python按元组中值的长度对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在排序元组列表时遇到困难.我想按列表中字符串的长度排序.
I am having difficulty sorting a list of tuples. I would like to sort by the length of a string in the list.
例如:
l = [(99,'bbc', 121),(33,'abcd', 231),(44,'zb', 148), (23,'abcde',221)]
如果我按元素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.
我可以使用lambda和cmp,
I can use a lambda and cmp,
l.sort(lambda x,y: cmp(len(x[1]), len(y[1])), reverse=True)
但是使用key和/或itemgetter是否有更优雅或更pythonic的方式?
but is there a more elegant, or pythonic way using key and/or itemgetter?
推荐答案
您可以使Lambda更加简单:
Well you can make the lambda simpler:
l.sort(key=lambda t: len(t[1]), reverse=True)
另外,不要使用list
作为变量名;它已经被内置函数使用了.
Also, don't use list
as a variable name; it's already taken by a built-in function.
这篇关于Python按元组中值的长度对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文