问题描述
我正在尝试将一些代码从Python移植到R,并且遇到了我无法完全理解的列表理解.这是一个类似于代码的玩具示例
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]]])]
好输出是两个数组的列表.我不明白的是for theta in thetai
子句.为什么?因为theta
是比thetai
大的数组. Theta
具有形状(5,2,2,3),但thetai
具有形状(2,2,3).那么,当代码显示for biggerthing in smallerthing
???
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
???
推荐答案
theta
引用列表推导中的新局部变量.它不再引用数组theta
.请注意,for
循环和列表理解之间的区别是列表理解中的变量i
是局部变量,而for循环中的i
也会覆盖外部变量.参见:
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
这篇关于异常的列表理解行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!