2015-12-02 264 views
2

我知道屬性映射(函數,列表)將函數應用於單個列表的每個元素。但是,如果我的函數需要多個列表作爲輸入參數,情況會怎樣呢?使用多個列表作爲函數的輸入參數(Python)

比如我想:

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] 

我將不勝感激如果有人能讓我知道這將如何成爲可能,或指向我的問題可能是一個鏈接在類似的情況下解答。

+0

如果你想要做的矢量數學運算,使用圖書館,如'numpy',特別是如果你要經常這樣做。 – Holt

回答

5

您可以使用operator.add

from operator import add 

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

小心,在python 3.x'map'上返回一個不是列表的生成器。 – Holt

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

快速而簡單:

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

0

而不是列表,而是使用numpy中的數組。 列表連接,而數組添加相應的元素。在這裏,我將輸入轉換爲numpy數組。您可以提供函數numpy數組並避免轉換步驟。

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) 

打印(RESULT1,結果2)

相關問題