Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回包含元组列表中最长单词的列表中的列表_Python - Fatal编程技术网

Python 返回包含元组列表中最长单词的列表中的列表

Python 返回包含元组列表中最长单词的列表中的列表,python,Python,我有一个元组列表: >>> [[x, y] for x, y in l1 if y == max_l1_len] [['three', 5]] >>> [[x, y] for x, y in l2 if y == max_l2_len] [['Those', 5], ['young', 5]] [('1',3),('2',3),('3',5)] [(“那些”,5),(“谁”,4),(“神”,3),(“爱”,4),(“成长”,4),(“年轻”,5)] 我想返

我有一个元组列表:

>>> [[x, y] for x, y in l1 if y == max_l1_len]
[['three', 5]]
>>> [[x, y] for x, y in l2 if y == max_l2_len]
[['Those', 5], ['young', 5]]
[('1',3),('2',3),('3',5)]
[(“那些”,5),(“谁”,4),(“神”,3),(“爱”,4),(“成长”,4),(“年轻”,5)]
我想返回每个列表中最长的单词,如果它们相等,则应按如下方式返回:

[["three", 5]]
[["Those", 5],["young", 5]]

如何实现这一点?

尝试使用列表理解:

>>> l1 = [('One', 3), ('two', 3), ('three', 5)]
>>> l2 = [('Those', 5), ('whom', 4), ('the', 3), ('gods', 4), ('love', 4), ('grow', 4), ('young', 5)]
>>> max_l1_len = max(y for _, y in l1)
>>> max_l2_len = max(y for _, y in l2)
>>> [(x, y) for x, y in l1 if y == max_l1_len]
[('three', 5)]
>>> [(x, y) for x, y in l2 if y == max_l2_len]
[('Those', 5), ('young', 5)]
或者,如果希望列表列表而不是元组列表:

>>> [[x, y] for x, y in l1 if y == max_l1_len]
[['three', 5]]
>>> [[x, y] for x, y in l2 if y == max_l2_len]
[['Those', 5], ['young', 5]]

假设每个单词的长度都是元组对的一部分,您可以使用条件列表来检查每个单词的最大单词长度:

max_word_length = max(tup[1] for tup in my_list)
[pair for pair in my_list 
 if pair[1] == max_word_length]
您还可以使用
过滤器

list(filter(lambda x: x[1] == max_word_length, my_list))