【发布时间】:2020-06-06 18:18:34
【问题描述】:
考虑以下命令:
elite_states = [s for i in range(len(states_batch))
if rewards_batch[i]>=reward_threshold for s in states_batch[i]]
我发现相当于下面的循环:
_l=[]
for i in range(len(states_batch)):
for s in states_batch[i]:
if rewards_batch[i]>=reward_threshold:
_l.append(s)
但是,我不明白第一个命令中s 之后的循环如何变成等效的外循环。我想了解命令的格式,以便了解它是如何工作的!
【问题讨论】:
-
一开始可能看起来倒退了,但是将列表理解中的最后一个循环作为内部循环,所以
i在范围内。尝试以相反的方式对它们进行排序,i的使用将在其声明之前。 -
如果您考虑一下,它们 (@ForceBru 所述循环的正确版本) 的顺序相同:outerloop -> if -> innerloop,唯一的改变的是结果's'的位置