0

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)]       
1
  • List comprehensions are for creating new lists, not for modifying existing lists. if you want to modify a list in-place, the idiomatic way is to just use a for-loop. Commented Oct 3, 2018 at 18:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.