簡體   English   中英

在Python理解的背景下,什么是“可迭代表達式”?

[英]What is a **iterable expression** in the context of Python comprehension?

醫生

但是,除了最左邊的for子句中的可迭代表達式之外,該理解是在單獨的隱式嵌套范圍內執行的。

理解的常見語法元素是:

comprehension ::=  expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]

我有什么

(如果出現問題,請糾正我)

考慮這個例子

[i**2 for i in range(3)]

整條線都是理解力。

其中i**2扮演表達式的角色,並且for i in range(3)中的i扮演comp_for的角色, i扮演target_list的角色, range(3)扮演的是or_test的角色。

什么是可迭代表達式

在這種情況下, i**2還是i是可迭代的表達式?

可迭代表達式大概是range(3) ,因為它是一個生成可迭代對象的表達式。

該文檔在范圍方面的含義是,根據當前局部范圍對定義要迭代的范圍的表達式 (在本例中為range(3) )進行評估。 然后, 在理解中的所有其他內容都在其自己的嵌套范圍內進行評估。

這類似於從解壓縮中獲得的for循環:

comprehension = []
# introduce i to local scope
# note that range(3) is being evaluated in terms of the current scope 
#    (OUTSIDE the loop) instead of the nested scope (INSIDE the loop)
for i in range(3):
    comprehension.append(i**2)
# remove i from local scope, as if the scope inside the for loop was nested
del i
# i is not present in the current scope
# evaluate range(3) in terms of the outer scope
# make a nested scope, and put i in it
comprehension = [i**2 for i in range(3)]
# once the comprehension is done executing, exit that nested scope
# i is not present in the current scope

通常在python中,整個函數都有自己的作用域,並且該函數中的各個代碼塊(例如,條件和循環)都共享相同的作用域。 但是,理解會創建一個內部范圍,一旦您離開該理解,它就會消失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM