首页 > 解决方案 > 循环如何在 python 的列表分配中工作?

问题描述

考虑以下命令:

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第一个命令中的循环如何成为等效的外循环。我想了解命令的格式,以便了解它是如何工作的!

标签: pythonlistloops

解决方案


我发现这相当于以下循环:

它不是。列表推导式的读取方式与普通嵌套循环相同。首先你循环range(len(states_batch)),然后,在这个循环内,你检查if rewards_batch[i]>=reward_threshold,接下来,在这个条件内,最后一个循环运行。

所以“扩展”版本看起来像这样:

_l=[]
for i in range(len(states_batch)):
  if rewards_batch[i]>=reward_threshold:  # `if` and the inner `for` are switched
    for s in states_batch[i]:
      _l.append(s)

在代码中,这与理解极为相似:

_l = [
  s
  for i in range(len(states_batch))
  if rewards_batch[i]>=reward_threshold
  for s in states_batch[i]
]

唯一的区别是推导中的循环是按顺序编写的(一个一个),但在扩展版本中,它们嵌套另一个中,推导中的最后一个循环嵌套最深。


推荐阅读