繁体   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