Search code examples
pythonlistpython-zip

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

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)]

Solution

  • 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)