我有两个清单:
C = [3, 2, 1]
D = [[0, 1, 2, 3], [0, 1, 2], [0, 1]]
我想实现这个结果:
E = [[0, 3, 6, 9], [0, 2, 4], [0, 1]]
仅使用列表推导。这可能吗?我被困在:
E = zip(C, D)
[i * E[0][0] for i in E[0][1]] which gives:
[0, 3, 6, 9]
但我无法修改它以申请第二个列表的其他元素
答案 0 :(得分:4)
是的,有可能:
>>> [[c * d_i for d_i in d] for c, d in zip(C, D)]
[[0, 3, 6, 9], [0, 2, 4], [0, 1]]
这里只需要两个循环,第一个循环遍历zip(C, D)
,第二个循环遍历每个D
答案 1 :(得分:2)
你几乎就在那里:它是一个嵌套的列表理解。另一个列表,[blah [j] for j in]
C = [3, 2, 1]
D = [[0, 1, 2, 3], [0, 1, 2], [0, 1]]
E = zip(C, D)
print [[i * E[j][0] for i in E[j][1]] for j in range(len(E))]
输出:
[[0, 3, 6, 9], [0, 2, 4], [0, 1]]
答案 2 :(得分:0)
如果您使用numpy
数组:
import numpy as np
np.array(C) * np.array(map(np.array, D))
# array([array([0, 3, 6, 9]), array([0, 2, 4]), array([0, 1])], dtype=object)
答案 3 :(得分:0)
我也会用itertools.startmap
来解决它:
>>> from itertools import starmap
>>>
>>> def multiply(x, lst):
return [x*i for i in lst]
>>> for item in it.starmap(f, zip(C,D)):
print(item)
[0, 3, 6, 9]
[0, 2, 4]
[0, 1]
OR:
>>> l = []
>>> for item in it.starmap(lambda x,y: [x*i for i in y], zip(C,D)):
l.append(item)
>>> l
[[0, 3, 6, 9], [0, 2, 4], [0, 1]]