python - 循环如何在 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
第一个命令中的循环如何成为等效的外循环。我想了解命令的格式,以便了解它是如何工作的!
解决方案
我发现这相当于以下循环:
它不是。列表推导式的读取方式与普通嵌套循环相同。首先你循环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]
]
唯一的区别是推导中的循环是按顺序编写的(一个接一个),但在扩展版本中,它们嵌套在另一个中,推导中的最后一个循环嵌套最深。
推荐阅读
- android - SVG url 图像未显示在 RecyclerView 中
- bash - 如何在bash脚本中根据html中的特定url自动查找并点击
- python - 限制/约束权重
- html - Gmail 剪辑 html 电子邮件,更新大小
- swift - 我在 Xcode 10 中打开了我的应用程序,现在在 9.4.1 中出现错误:SDKApplicationDelegate (FacebookCore)
- jena - Jena 数据集监听器
- python - Python 无法导入现有文件
- java - 在 MySQL 数据库中建立连接的代码
- tensorflow - 指示代理端口号时如何从datalab打开TensorBoard
- html - CSS button that auto adjusts to the window size