首页 > 解决方案 > 不寻常的列表理解行为

问题描述

我正在尝试将一些代码从 Python 移植到 R,但遇到了我无法完全理解的列表理解。这是一个类似于代码的玩具示例

import numpy as np
theta = np.random.rand(5, 2, 2, 3)
thetai = theta[0]

logp = [theta[np.newaxis, ...] for theta in thetai]

如果我运行并打印我得到的结果:

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是一个比 更大的数组thetaiTheta具有形状 (5,2,2,3) 但thetai具有形状 (2,2,3)。那么当代码说for biggerthing in smallerthing???时,列表理解实际上在做什么?

标签: pythonnumpyfor-looplist-comprehension

解决方案


theta引用列表推导中的新局部变量;它不再引用数组theta。请注意,for循环和列表推导之间的区别在于列表推导中的变量i是局部变量,而ifor 循环中的变量也会覆盖外部变量。看:

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

推荐阅读