如何将压缩列表项相互相乘?

How to multiply a zipped list's items with eachother?

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

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

提前感谢所有提供帮助的人!

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

这应该可以满足您的要求:

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]

使用 split and zip should be straightforward. then a list comprehension 创建列表。

试试这个

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