本文介绍了Python:产生清单,这是两个清单的总和,逐项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个列表:

a=[1,2,3,4,5]
b=[5,4,3,2,1]

我想创建第三个,它将是给定的两个的线性和:

I want to create a third one which will be linear sum of two given:

c[i]==a[i]+b[i]
c==[6,6,6,6,6]

是否可以使用"for"构造函数?像:

Is it possible to do with 'for' constructor? Like:

c = [aa+bb for aa in a for bb in b]

(显然返回的不是我想要的)

(which obviously returns not what I want)

推荐答案

使用zip():

>>> a = [1,2,3,4,5]
>>> b = [5,4,3,2,1]
>>> c = [x+y for x,y in zip(a, b)]
>>> c
[6, 6, 6, 6, 6]

或:

>>> c = [a[i] + b[i] for i in range(len(a))]
>>> c
[6, 6, 6, 6, 6]

c = [aa+bb for aa in a for bb in b]类似于:

 for aa in a:
     for bb in b:
           aa+bb

这表示从a中选择1,然后遍历b的所有元素,同时将它们添加到1中,然后从a中选择2,然后再次遍历a的所有值b将它们添加到2时,这就是为什么未获得预期输出的原因.

this means , select 1 from a and then loop through all elements of b while adding them to 1, and then choose 2 from a and then again loop through all values of b while adding them to 2, that's why you were not getting expected output.

这篇关于Python:产生清单,这是两个清单的总和,逐项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 19:27