簡體   English   中英

使用多個列表作為函數的輸入參數(Python)

[英]Use multiple lists as input arguments of a function (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]

如果有人能讓我知道這是怎么可能的,或者我指的是一個可以在類似情況下回答我的問題的鏈接,我將不勝感激。

您可以使用operator.add

from operator import add

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

您可以使用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]

快速簡單:

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

而不是列表,而是使用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)

print(result1,result2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM