【问题标题】:Use multiple lists as input arguments of a function (Python)使用多个列表作为函数的输入参数 (Python)
【发布时间】:2015-12-02 14:52:31
【问题描述】:

我知道属性 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]

如果有人能让我知道这怎么可能,我将不胜感激,或者指向一个链接,我的问题可以在类似的情况下得到解答。

【问题讨论】:

  • 如果您想对向量进行数学运算,请使用 numpy 之类的库,特别是如果您打算经常这样做。

标签: python function input multiple-arguments


【解决方案1】:

你可以使用operator.add

from operator import add

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

【讨论】:

  • 小心,在 python 3.x map 返回一个生成器而不是一个列表。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    快速简单:

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

    【讨论】:

      【解决方案4】:

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

      打印(结果1,结果2)

      【讨论】:

        猜你喜欢
        • 2022-07-04
        • 1970-01-01
        • 1970-01-01
        • 2011-06-26
        • 1970-01-01
        • 2022-11-15
        • 2018-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多