列表理解同时迭代两个变量 [英] List comprehension iterate two variables at the same time
本文介绍了列表理解同时迭代两个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能使用列表理解同时迭代两个变量,同时增加两个变量的循环位置.请参见下面的示例:
Is it possible that with the use of list comprehension to iterate through two variables at the same time increasing the loop position in both at the same time. See example below:
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = [i+j for i in a for j in b] # This works but the output is not what it would be expected.
预期输出为 c = [7, 9, 11, 13, 15]
(来自 a 的第 n 个元素 + 来自 b 的第 n 个元素)
expected output is c = [7, 9, 11, 13, 15]
(n'th element from a + n'th element from b)
谢谢.
推荐答案
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = map(sum, zip(a, b))
print c
#Output
[7, 9, 11, 13, 15]
这篇关于列表理解同时迭代两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文