Python: Create a list that is a sum of two lists in different ways

Let's say I have two lists:

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

I want to create a third that will be the linear sum of two:

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

Can the 'for' constructor be used? For instance:

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

(which explicitly returns not what I want)

+6
source share
5 answers

Use 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] 

or

 >>> 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] looks something like this:

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

this means select 1 from a and then skip all the elements of b by adding them to 1 and then select 2 from a and then skip all the values โ€‹โ€‹of b again by adding them to 2 so you did not get the expected result.

+21
source
 a=[1,2,3,4,5] b=[5,4,3,2,1] [x+y for x,y in zip(a,b)] [6, 6, 6, 6, 6] OR map(lambda x,y:x+y, a, b) [6, 6, 6, 6, 6] 
+5
source
 [ay + be for ay, be in zip(a, b)] 
+2
source
  sums = [a[i]+b[i] for i in range(len(a))] 
+1
source

I don't know what you are trying to do, but you can easily do what you requested with numpy. I'm just not sure if you really want to add this extra dependency to your code.

-1
source

Source: https://habr.com/ru/post/920077/


All Articles