在n个不相等的列表中查找最高值

时间:2018-01-08 19:09:38

标签: python list

我列出了n多个列表。

data = [
    [1, 2, 3, 4, 5, 6, 7, 8],
    [2, 6, 3, 5, 9, 1, 1, 1, 2, 4, 5],
    [8, 1, 4, 1, 2, 3, 4, 2, 5]
    [3, 9, 1, 2, 2, 1, 1, 5, 9, 3]
]

如何有效地比较它们并生成一个总是包含当前位置最高值的列表? 我不知道如何做到这一点,因为每个列表的边界都不同。

上述示例的输出应该是包含以下值的列表:

[8,9,4,5,9,6,7,8,9,4,5]

5 个答案:

答案 0 :(得分:4)

最常用的方法是转置2D列表并在转置列表中的每一行上调用max。但在您的情况下,您正在处理参差不齐的列表,因此无法在此处直接应用zip(仅将其压缩到最短列表)。

相反,使用itertools.zip_longestizip_longest用于python 2),然后使用max -

应用map
from itertools import zip_longest
r = list(map(max, zip_longest(*data, fillvalue=-float('inf'))))

或者,使用@Peter DeGlopper's suggestion,列表理解 -

r = [max(x) for x in zip_longest(*data, fillvalue=-float('inf'))]

print(r)
[8, 9, 4, 5, 9, 6, 7, 8, 9, 4, 5]

在这里,我使用fillvalue参数来填充负无穷大的缺失值。中间结果看起来像这样 -

list(zip_longest(*data, fillvalue=-float('inf')))

[(1, 2, 8, 3),
 (2, 6, 1, 9),
 (3, 3, 4, 1),
 (4, 5, 1, 2),
 (5, 9, 2, 2),
 (6, 1, 3, 1),
 (7, 1, 4, 1),
 (8, 1, 2, 5),
 (-inf, 2, 5, 9),
 (-inf, 4, -inf, 3),
 (-inf, 5, -inf, -inf)]

现在,应用max变得简单明了 - 只需在每行上执行即可。

答案 1 :(得分:2)

在这种情况下,

zip_longest是你的朋友。

from itertools import zip_longest

data = [
    [1, 2, 3, 4, 5, 6, 7, 8],
    [2, 6, 3, 5, 9, 1, 1, 1, 2, 4, 5],
    [8, 1, 4, 1, 2, 3, 4, 2, 5],
    [3, 9, 1, 2, 2, 1, 1, 5, 9, 3],
]

output = list()

for x in zip_longest(*data, fillvalue=0):
  output.append(max(x))

print(output)
>>> [8, 9, 4, 5, 9, 6, 7, 8, 9, 4, 5]

答案 2 :(得分:2)

添加pandas解决方案

import pandas as pd 

pd.DataFrame(data).max().astype(int).tolist()
Out[100]: [8, 9, 4, 5, 9, 6, 7, 8, 9, 4, 5]

答案 3 :(得分:1)

您可以使用itertools.izip_longest(Python3中的itertools.zip_longest):

Python2:

import itertools
data = [
[1, 2, 3, 4, 5, 6, 7, 8],
[2, 6, 3, 5, 9, 1, 1, 1, 2, 4, 5],
[8, 1, 4, 1, 2, 3, 4, 2, 5],
[3, 9, 1, 2, 2, 1, 1, 5, 9, 3],
]
new_data = [max(filter(lambda x:x, i)) for i in itertools.izip_longest(*data)]

输出:

[8, 9, 4, 5, 9, 6, 7, 8, 9, 4, 5]

Python3:

import itertools
data = [
[1, 2, 3, 4, 5, 6, 7, 8],
[2, 6, 3, 5, 9, 1, 1, 1, 2, 4, 5],
[8, 1, 4, 1, 2, 3, 4, 2, 5],
[3, 9, 1, 2, 2, 1, 1, 5, 9, 3],
]
new_data = [max(filter(None, i)) for i in itertools.zip_longest(*data)]

答案 4 :(得分:1)

你不需要任何外部模块,只需使用一些逻辑就可以了:

data = [
    [1, 2, 3, 4, 5, 6, 7, 8],
    [2, 6, 3, 5, 9, 1, 1, 1, 2, 4, 5],
    [8, 1, 4, 1, 2, 3, 4, 2, 5],
    [3, 9, 1, 2, 2, 1, 1, 5, 9, 3]
]

new_data={}
for j in data:
    for k,m in enumerate(j):
        if k not in new_data:
            new_data[k] = [m]
        else:
            new_data[k].append(m)




final_data=[0]*len(new_data.keys())

for key,value in new_data.items():
    final_data[key]=max(value)

print(final_data)

输出:

[8, 9, 4, 5, 9, 6, 7, 8, 9, 4, 5]