简体   繁体   English

循环如何在 python 的列表分配中工作?

[英]How do loops work in list assignments in python?

Consider the following command:考虑以下命令:

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

I found that is equivalent to the following loop:我发现这相当于以下循环:

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

However I don't get how the loop after s in the first command becomes the outer loop in its equivalent.但是,我不明白第一个命令中s之后的循环如何成为等效的外循环。 I want to understand the format of the command so I get how it works!我想了解命令的格式,以便了解它是如何工作的!

I found that is equivalent to the following loop:我发现这相当于以下循环:

It isn't.它不是。 List comprehensions are read in the same way as ordinary nested loops.列表推导式的读取方式与普通嵌套循环相同。 First you loop over range(len(states_batch)) , then, inside this loop , you check if rewards_batch[i]>=reward_threshold , next, inside this condition , the last loop is ran.首先你循环range(len(states_batch)) ,然后,在这个循环中,你检查if rewards_batch[i]>=reward_threshold ,接下来,在这个条件中,最后一个循环运行。

So the "expanded" version looks like this:所以“扩展”版本看起来像这样:

_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)

In code, this is extremely similar to the comprehension:在代码中,这与理解极为相似:

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

The only difference is that loops in comprehensions are written sequentially (one after the other), but in the expanded version they become nested one inside the other, the last loop in the comprehension being nested the deepest.唯一的区别是推导式中的循环是按顺序编写的(一个一个),但在扩展版本中,它们嵌套在另一个中,推导式中的最后一个循环嵌套最深。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM