python - 不寻常的列表理解行为
问题描述
我正在尝试将一些代码从 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
是一个比 更大的数组thetai
。Theta
具有形状 (5,2,2,3) 但thetai
具有形状 (2,2,3)。那么当代码说for biggerthing in smallerthing
???时,列表理解实际上在做什么?
解决方案
theta
引用列表推导中的新局部变量;它不再引用数组theta
。请注意,for
循环和列表推导之间的区别在于列表推导中的变量i
是局部变量,而i
for 循环中的变量也会覆盖外部变量。看:
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
推荐阅读
- sql - 我想获得基于两列交集的两个 Select 语句的交集结果
- excel - 如何让用户在另一个工作表中选择单元格,然后粘贴到它,在 Excel 中使用 VBA
- python - 如何从机器响应中提取或解包日期时间?
- azure - Azure Data Lake 的 Spark 谓词下推、过滤和分区修剪
- mysql - 如果 COUNT(DISTINCT COLNAME)>1 则选择所有行
- angular - RXJS 如何延迟每个 observable(http 请求)并合并所有请求输出
- flutter - 如何在 Flutter 中捕获 SQLITE 异常?
- sql - 我想从同一列的特定数据中选择一个内部进行计算。这可能吗?
- ruby - 在 Ruby 中,`self.i` 和 `@i` 有区别吗?
- python - 截断表并将数据帧插入 SQL,仅当数据帧可以成功插入时