Python:在列表理解中使用嵌套循环修改列表

时间:2018-10-03 18:08:47

标签: python list-comprehension nested-loops

我有一部分代码类似于以下内容:

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

1 个答案:

答案 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)]

但是真正的问题是-为什么?您正在增加阅读和/或维护的难度,并且在绩效部门工作不多。