Kim Shutter
Kim Shutter

Reputation: 187

Python: modifying list with nested loops in list comprehension

I have part of a code that does something analogous to the following:

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

Since both loop are modifying a list, is there a way for me to translate that to list comprehension? I have been trying variations of the following, with no success:

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

Upvotes: 0

Views: 115

Answers (1)

zwer
zwer

Reputation: 25789

If you insist doing it with a single list comprehension, I guess you can do something like:

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

Or:

test[:] = [v * norm[i] * reduce(mul, (my_dic[(i, j)] for j in range(5)), 1)
           for i, v in enumerate(test)]

But the real question is - why? You're making it harder to read and/or maintain and you're not getting much in the performance department.

Upvotes: 1

Related Questions