这个python for循环实际上在做什么

时间:2020-05-16 13:21:51

标签: python for-loop indexing

我正在尝试将一些代码从Python移植到R,并且在我从未见过的Python代码中遇到过for的使用,并且无法通过谷歌搜索找到答案:< / p>

代码行是: logp = [theta[np.newaxis, ...] for theta in thetai]

我了解theta[np.newaxis, ...]部分,但出于某些原因我无法弄清for子句

我在这里做了一个可复制的小例子:

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

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

产生此输出:

logp
Out[406]: 
[array([[[0.305, 0.071, 0.483],
         [0.005, 0.627, 0.24 ]]]),
 array([[[0.648, 0.524, 0.254],
         [0.257, 0.367, 0.796]]])]

我不明白两件事。 1. for子句在做什么-子集化数组的手段吗? 2.当theta实际上是thetai的子集时,如何在thetai中使用theta? ?

在此感谢您的帮助,在此先感谢

1 个答案:

答案 0 :(得分:2)

在python中称为列表理解。基本思想是以更紧凑的方式编写语句。 代替

arr = []
for x in range(10):
  arr.append(x)

我们可以写

arr = [ x for x in range(10)]

进一步了解此here