简体   繁体   English

如何比较列表中的元素?

[英]How to compare elements in list-of-lists?

I have a list which contains list of elements(the number of elements in each inner list are not same) and I want to group all the elements in same index into separate groups and return maximum values in each group: for example,我有一个包含元素列表的列表(每个内部列表中的元素数量不同),我想将同一索引中的所有元素分组到单独的组中并返回每个组中的最大值:例如,

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

I want to group these elements like this,我想像这样对这些元素进行分组,

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

the expected result is the maximum values of each list in groups: 106,213 and 317预期结果是组中每个列表的最大值:106,213 和 317

I tried to group elements using following code:我尝试使用以下代码对元素进行分组:

w = zip(*elements)
result_list = list(w)
print(result_list)

output I got is output 我得到的是

[(89, 106, 87)]

You can use itertools.zip_longest with fillvalue=float("-inf") :您可以将itertools.zip_longestfillvalue=float("-inf")一起使用:

from itertools import zip_longest

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

out = [max(t) for t in zip_longest(*elements, fillvalue=float("-inf"))]
print(out)

Prints:印刷:

[106, 213, 317]

NOTE: zip() won't work here, because (as you stated) the number of elements in each inner list are not same.注意: zip()在这里不起作用,因为(如您所述)每个内部列表中的元素数量不同。 With zip_longest() the missing elements are substituted with fillvalue , in this case -infinity (and -infinity will be always the lowest value in the max() function)使用zip_longest()缺失的元素被替换为fillvalue ,在这种情况下-infinity (并且-infinity将始终是max()函数中的最小值)

Try creating a dictionary keyed with the index of each sub list, then turning the values into the new list, then map to max:尝试使用每个子列表的索引创建一个字典,然后将values转换为新列表,然后将 map 设置为最大值:

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_d : i_d

defaultdict(<class 'list'>, {0: [89, 106, 87], 1: [213, 191], 2: [317, 314]})

maxes : maxes

[106, 213, 317]

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

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