问题
I'm trying to port some code from Python to R and I've come across a list comprehension I cannot fully understand. Here is a toy example analogous to the code
import numpy as np
theta = np.random.rand(5, 2, 2, 3)
thetai = theta[0]
logp = [theta[np.newaxis, ...] for theta in thetai]
If I run and print the results I get:
print(logp)
[array([[[0.779, 0.461, 0.766],
[0.245, 0.189, 0.045]]]), array([[[0.229, 0.288, 0.173],
[0.011, 0.541, 0.528]]])]
Ok output is a list of two arrays. What I cannot understand is the for theta in thetai clause. Why? Because theta is a bigger array than thetai. Theta has shape (5,2,2,3) but thetai has shape (2,2,3). So what is the list comprehension actually doing when the code says for biggerthing in smallerthing ???
回答1:
theta refers to a new local variable within the list comprehension; it does not refer to the array theta anymore. Note that the difference between a for loop and a list comprehension is that the variable i in the list comprehension is a local variable, whereas the i in the for loop will overwrite the outer variables too. See:
i = -1
[i for i in range(10)] # Outputs [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(i) # Prints -1
i = -1
for i in range(10):
pass
print(i) # Prints 9
来源:https://stackoverflow.com/questions/61866304/unusual-list-comprehension-behaviour