温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Multiply list of lists with elements of multiplier list Python
for-loop list matrix python

其他 - 将列表与乘数列表Python元素相乘

发布于 2020-04-12 10:36:27

我想将下面的列表与乘数列表的元素相乘。因此,multiplier [0]乘以列表列表中的第一个列表,multiplier [1]乘以列表列表中的第二个列表,依此类推。

谢谢!

到目前为止,我已经尝试过了:

[a*b for a,b in zip(multiplier,list_of_lists)]

这是列表的列表:

[[0, 0, 1, 1], 
[1, 0, 0, 0], 
[1, 1, 1, 1], 
[1, 2, 0, 1]]

乘数列表:

[1.0, 2.0, 0.0, 0.41503749927884376]

查看更多

提问者
rex9311
被浏览
95
Olvin Roght 2020-02-02 21:07

如果将代码从列表理解转换为简单循环,您将看到问题所在:

result = []
for a, b in zip(multiplier, list_of_lists):
    result.append(a * b)  # appends a copies of list b

绝对不是您要执行的操作。您需要嵌套循环才能遍历内部列表的各项:

result = []
for multiplier, sub_list in zip(multipliers, list_of_lists):
    new_list = []
    for item in sub_list:
        new_list.append(multiplier * item)
    result.append(new_list)

或者,您可以使用嵌套列表推导来更短地编写它(可以给变量起更短的名称以使其看起来更“紧凑”):

result = [[multiplier * item for item in sub_list] for multiplier, sub_list in zip(multipliers, list_of_lists)]