2

I know that the property map(function,list) applies a function to each element of a single list. But how would it be if my function requires more than one list as input arguments?.

For example I tried:

   def testing(a,b,c):
      result1=a+b
      result2=a+c
      return (result1,result2)

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

result1,result2=testing(a,b,c)

But this only concatenates the arrays:

result1=[1,2,3,4,1,1,1,1]
result2=[1, 2, 3, 4, 2, 2, 2, 2]

and what I need is the following result:

result1=[2,3,4,5] 
result2=[3,4,5,6]

I would be grateful if somebody could let me know how would this be possible or point me to a link where my question could be answered in a similar case.

Sarah
  • 325
  • 6
  • 17
  • If you want to do mathematical operations on vectors, use a library such as `numpy`, especially if you are going to do this often. – Holt Dec 02 '15 at 15:04

4 Answers4

4

You can use operator.add

from operator import add

def testing(a,b,c):
    result1 = map(add, a, b)
    result2 = map(add, b, c)
    return (result1, result2)
CubeRZ
  • 574
  • 5
  • 9
4

You can use zip:

def testing(a,b,c):
    result1=[x + y for x, y in zip(a, b)]
    result2=[x + y for x, y in zip(a, c)]
    return (result1,result2)

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

result1,result2=testing(a,b,c)
print result1 #[2, 3, 4, 5]
print result2 #[3, 4, 5, 6]
MaTh
  • 217
  • 1
  • 12
2

Quick and simple:

result1 = [a[i] + b[i] for i in range(0,len(a))]
result2 = [a[i] + c[i] for i in range(0,len(a))]

(Or for safety you can use range(0, min(len(a), len(b)))

Paul Siegel
  • 1,401
  • 13
  • 36
0

Instead of list, use array from numpy instead. list concatenate while arrays add corresponding elements. Here I converted the input to numpy arrays. You can feed the function numpy arrays and avoid the conversion steps.

def testing(a,b,c):
    a = np.array(a)
    b = np.array(b)
    c = np.array(c)
    result1=a+b
    result2=a+c
    return (result1,result2)

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

result1,result2=testing(a,b,c)

print(result1, result2)

Huy Nguyen
  • 73
  • 5