[英]How do loops work in list assignments in 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]
]
唯一的區別是推導式中的循環是按順序編寫的(一個接一個),但在擴展版本中,它們嵌套在另一個中,推導式中的最后一個循環嵌套最深。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.