2016-02-06 108 views
-1

可以说我有2所列出:找到两个列表的索引明智的最大值

L1 = [2,4,1,6] 
L2 = [1,5,2,3] 

输出应该是包含在L1或L2发现基于自己的立场上最大号的新名单。

输出示例:

L3 = [2, 5, 2, 6] 

怎么办呢?

+5

你如何试图做到这一点,这有什么问题呢? – jonrsharpe

+0

输入?或输出?你试过的示例代码和它不适合你的原因如何? – Vorsprung

+0

我将以[我如何在Python中并行遍历两个列表?](http://stackoverflow.com/q/1663807)开始您的工作。添加一个[list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)和'max()'函数,你就可以在一行中找到解决方案。 –

回答

3

一个可能的解决方案是压缩您的列表,然后在施加最大的操作元素,明智的,它可以在Python通过呼叫通过列表解析来获得功能map

L1 = [2,4,1,6] 
L2 = [1,5,2,3] 
L3 = map(max, zip(L1, L2)) # python2 
L3 = list(map(max, zip(L1, L2))) # python3 

或更Python

L3 = [max(l1, l2) for l1, l2 in zip(L1, L2)] 
使用拆包操作

或位较短的版本

L3 = [max(*l) for l in zip(L1, L2)] 
1

这是一个快速修复,在一组迭代中!

list_a = [2,4,1,6] 
list_b = [1,5,2,3] 

max_list = [value if list_b[index]<value else list_b[index] for index, value in enumerate(list_a)] 

print(max_list) 

显示:[2, 5, 2, 6]