How to compare elements in list-of-lists?

244 Views Asked by At

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

I tried to group elements using following code:

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

output I got is

[(89, 106, 87)]
2

There are 2 best solutions below

0
On BEST ANSWER

You can use itertools.zip_longest with fillvalue=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. 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)

0
On

Try creating a dictionary keyed with the index of each sub list, then turning the values into the new list, then map to 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_d:

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

maxes:

[106, 213, 317]