Michael
Michael

Reputation: 5335

Get maximum values in three or more lists of different lengths

I need to resize the columns in the Excel datasheet with Python's xlsxwriter. For this purpose I've prepared three lists of maximum text lengths in dataframe columns.

l1 = [5, 10, 12, 3, 6, 2]
l2 = []
l3 = [6, 9, 11, 5, 4, 4, 8, 7]

I need to get the maximum values in these lists so that the resulting list will look like this:

common = [6, 10, 12, 5, 6, 4, 8, 7]

I know I should write here my own solution, but it's trivial: we should find the list with maximum length, then compare each value with each other list if its length allows that. But is there a more optimal way?

Upvotes: 0

Views: 186

Answers (1)

Selcuk
Selcuk

Reputation: 59315

If they are always guaranteed to be positive numbers, you can zip_longest them using 0 as a fillvalue:

>>> from itertools import zip_longest
>>> list(map(max, zip_longest(l1, l2, l3, fillvalue=0)))
[6, 10, 12, 5, 6, 4, 8, 7]

If there can be negative numbers as well, you can use negative infinity instead of 0:

>>> from math import inf
>>> list(map(max, zip_longest(l1, l2, l3, fillvalue=-inf)))
[6, 10, 12, 5, 6, 4, 8, 7]

Upvotes: 6

Related Questions