Unusual list comprehension behaviour

亡梦爱人 提交于 2020-08-10 22:28:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!