【问题标题】:How to multiply a zipped list's items with eachother?如何将压缩列表项相乘?
【发布时间】:2020-10-22 17:00:56
【问题描述】:

我正在做一个练习,我创建了一个函数,该函数接收两个列表并在单独的单个列表中返回相同索引处的项目的乘法。示例:

transform("1 5 3", "2 6 -1")
#should return
[2, 30, -3]

为了清楚起见,程序获取索引 1、2 和 3 处的项目并将它们相乘,如下所示:

(1 * 2), (5 * 6), (3 * -1)

现在,我面临的问题是在程序中必须使用zip()函数,我还没有正确使用。

我已经制作了一个成功完成一般任务的程序,但我想不出一个使用压缩列表的解决方案。谁能帮我解决这个问题?我有一个想法,我可以使用我在 map() 函数中创建的压缩列表“q”,但我不知道如何。

这是我的程序:

def transform(s1, s2):
    i = 0

    s = s1.split(' ')
    d = s2.split(' ')

    while i < len(s):
        try:
            s[i] = int(s[i])
            d[i] = int(d[i])
            i += 1
        except ValueError:
            break

    print(s, d)

    q = list(zip(s, d))
    print(q)

    final = list(map(lambda x, y: x * y, s, d))

    return final

def main():
    print(transform("1 5 3", "2 6 -1"))

if __name__ == "__main__":
    main()

提前感谢任何提供帮助的人!

【问题讨论】:

    标签: python python-3.x lambda list-comprehension


    【解决方案1】:

    这应该做你想做的:

    def transform(a, b):
         return [int(i) * int(j) for i, j in zip(a.split(), b.split())]
    
    
    
    a = "1 5 3"
    b = "2 6 -1"
    print(transform(a, b))  # [2, 30, -3]
    

    splitzip 的使用应该很简单。然后 list comprehension 创建列表。

    【讨论】:

      【解决方案2】:
      s1 = '1 5 3'
      s2 = '2 6 -1'
      
      def transform(s1, s2):
          return [x*y for x,y in zip([int(x) for x in s1.split()],
                                     [int(x) for x in s2.split()])]
      
      transform(s1,s2)
      

      输出

      [2, 30, -3]
      

      【讨论】:

        【解决方案3】:
        1. 要轻松地将一个字符串转换为您使用的字符串列表map

          s = "1 2 3"
          list(map(int, s.split())) 
          > [1, 2, 3]
          
        2. 然后你压缩 2 个列表

          zip(map(int, s1.split()), map(int, s2.split()))
          > [(1, 2), (5, 6), (3, -1)]`
          
        3. 最后你想对每一对应用lambda x: x[0] * x[1],或者operator.mul(x[0], x[1])

        from operator import mul
        
        def transform(s1, s2):
            return list(map(lambda x: mul(*x), zip(map(int, s1.split()), map(int, s2.split()))))
        

        【讨论】:

          【解决方案4】:

          试试这个

          item1, item2 =  "1 5 3", "2 6 -1"
          
          def transform(i1, i2):
              return [int(x) * int(y) for x, y in zip(i1.split(" "), i2.split(" "))]
          
          print(transform(item1, item2))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-11-29
            • 1970-01-01
            • 2018-11-01
            • 1970-01-01
            • 1970-01-01
            • 2020-12-14
            • 2011-05-05
            • 1970-01-01
            相关资源
            最近更新 更多