我有一部分代码类似于以下内容:
import numpy as np
N = 10
test = [1] * N
np.random.seed(123)
norm = np.random.rand(N)
my_dic = {(k, kk):np.random.rand(1) for k,_ in enumerate(test) for kk in range(5)}
for i, _ in enumerate(test):
test[i] *= norm[i]
for j in range(5):
test[i] *= my_dic[(i, j)]
由于两个循环都在修改列表,所以我有办法将其转换为列表理解吗?我一直在尝试以下变化,但没有成功:
import numpy as np
N = 10
test = [1] * N
np.random.seed(123)
norm = np.random.rand(N)
my_dic = {(k, kk):np.random.rand(1) for k,_ in enumerate(test) for kk in range(5)}
test = [val for val in norm]
test = [test[i] * my_dic[(i, j)] for i, _ in enumerate(test) for j in range(5)]
答案 0 :(得分:1)
如果您坚持使用单列表理解方式进行操作,我想您可以执行以下操作:
from operator import mul
from functools import reduce # comment out on Python 2.x
test[:] = [reduce(mul, [v * norm[i]] + [my_dic[(i, j)] for j in range(5)], 1)
for i, v in enumerate(test)]
或者:
test[:] = [v * norm[i] * reduce(mul, (my_dic[(i, j)] for j in range(5)), 1)
for i, v in enumerate(test)]
但是真正的问题是-为什么?您正在增加阅读和/或维护的难度,并且在绩效部门工作不多。