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.

1
  • If you want to do mathematical operations on vectors, use a library such as numpy, especially if you are going to do this often. Commented Dec 2, 2015 at 15:04

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Be careful, on python 3.x map returns a generator not a list.
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]

Comments

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)))

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.