异常的列表理解行为 [英] Unusual list comprehension behaviour

查看:70
本文介绍了异常的列表理解行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些代码从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

这篇关于异常的列表理解行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆