2

プロパティ map(function,list) が単一のリストの各要素に関数を適用することを知っています。しかし、関数が入力引数として複数のリストを必要とする場合はどうなるでしょうか?.

たとえば、私は試しました:

   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)

しかし、これは配列を連結するだけです:

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

そして、私が必要とするのは次の結果です:

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

誰かがこれがどのように可能になるかを教えてくれたり、同様のケースで私の質問に答えることができるリンクを教えてくれたりするとありがたい.

4

4 に答える 4

4

使用できます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]
于 2015-12-02T15:00:50.050 に答える
4

使用できますoperator.add

from operator import add

def testing(a,b,c):
    result1 = map(add, a, b)
    result2 = map(add, b, c)
    return (result1, result2)
于 2015-12-02T14:59:29.500 に答える
2

素早く簡単:

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

(または安全のために使用できますrange(0, min(len(a), len(b))

于 2015-12-02T15:11:32.107 に答える