Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Python Zip - Fatal编程技术网

Python 如何比较列表列表中的元素?

Python 如何比较列表列表中的元素?,python,list,python-zip,Python,List,Python Zip,我有一个包含元素列表的列表(每个内部列表中的元素数量不相同),我希望将同一索引中的所有元素分组为单独的组,并在每个组中返回最大值: 比如说, elements = [[89, 213, 317], [106, 191, 314], [87]] 我想这样把这些元素分组 groups = [[89,106,87],[213,191],[317,314]] 预期结果是每组中每个列表的最大值:106、213和317 我尝试使用以下代码对元素进行分组: w = zip(*elements) resul

我有一个包含元素列表的列表(每个内部列表中的元素数量不相同),我希望将同一索引中的所有元素分组为单独的组,并在每个组中返回最大值: 比如说,

elements = [[89, 213, 317], [106, 191, 314], [87]]
我想这样把这些元素分组

groups = [[89,106,87],[213,191],[317,314]]
预期结果是每组中每个列表的最大值:106、213和317

我尝试使用以下代码对元素进行分组:

w = zip(*elements)
result_list = list(w)
print(result_list)
我得到的输出是

[(89, 106, 87)]

尝试创建一个带有每个子列表索引的字典,然后将
值转换为新列表,然后映射到max:

from collections import defaultdict

elements = [[89, 213, 317], [106, 191, 314], [87]]

i_d = defaultdict(list)

for sub in elements:
    for i, v in enumerate(sub):
        i_d[i].append(v)

maxes = list(map(max, i_d.values()))
print(maxes)
i\u d

defaultdict(<class 'list'>, {0: [89, 106, 87], 1: [213, 191], 2: [317, 314]})
您可以与
fillvalue=float(“-inf”)
一起使用:

从itertools导入zip\u
元素=[[89213317],[106191314],[87]]
out=[t的最大值(t)表示zip中的t_最长(*元素,fillvalue=float(“-inf”)]
打印(输出)
印刷品:

[106213317]

注意:
zip()。使用
zip_longest()

[106, 213, 317]