[英]Python: loop in elif condition
我正在運行Python 3。
是否有可能為elif
設置循環? 這是我想要實現的基本想法。 列表中的項目數不是恆定的。
if some_condition:
do this
elif [ x.method() for x in list ]:
do this to x
else:
do something else
現在,我想到了這個:
if some_condition:
do this
for x in list:
if x.method():
do this to x
break
但是我試圖避免運行所有的if語句,其中有很多東西正在進行中。 我想特別在elif
部分得到它,而不是在else
。
看起來我需要的是any( x.method() for x in list )
但也引用了x
這樣我就可以在條件為真時使用x
。
這是我想要再次獲得的整個概念:
if condition:
do this
elif list[0].method():
do this to list[0]
elif list[1].method():
do this to list[1]
...
elif list[n].method():
do this to list[n]
else:
do this
其中method()
是一些返回True
或False
方法, n
是列表的大小而不是常量。
if [ x.method() for x in list ]:
你問,有可能嗎? 是。 但是它做了什么? 可能不是你想要的。
對於列表中的項目數,它將在結果列表中構造一個值。 對於列表值,只有零長度的列表將為False。 [False,False,False]為True,因此將執行條件的主體。
如果x.method()應該影響以下條件決策,您可能正在尋找all()或any() 。
if all(x.method() for x in list): # will require that every *x.method* call return truth.
同樣,你可能想要
if any(x.method() for x in list): # only one required. May not do every .method if it can stop early. Beware side-effects.
我不認為你想要什么 - 完全在elif
- 它是可能的。 您必須評估列表中是否存在any
此類值,然后將其綁定到條件中的 x
。 據我所知,這在Python的語法中是不可能的。 您不能在條件中進行賦值 ,並且雖然列表推導中的循環變量可以 “泄漏”到外部范圍,但對於生成器來說卻不是這樣。
>>> if any(x for x in range(10) if x >= 5):
... print x
NameError: name 'x' is not defined
>>> if any([x for x in range(10) if x >= 5]):
... print x
9
在第二種情況(列表)中,我們引用了x
,但它是整個列表中的最后一個值,而在第一種情況下(生成器), x
根本無法解析。
取而代之的是,這里的另一種變體,使用生成表達式組合for
與if
,並添加else
的for
對enumate最終else
條款。
if some_condition:
print "do this"
else:
for x in (x for x in lst if foo(x)):
print "do this to", x
break
else:
print "do something else"
我現在明白了。 做出更新編輯所說的Pythonic方法是在找到第一個項目並對其進行操作后進行for循環並突破,並使用循環中幾乎未知和未使用的“其他”。
由於“for / else”習慣用法很少使用,因此您需要為將來的讀者添加關於它的評論。
if some_test:
first_action()
else:
for item in list:
if item.method():
do_this(item)
break # process no more of list
else: # for-else only entered if no break from the list!
final_action()
閱讀Python教程中的循環過程 。
你不可能做你想做的事情,但是你可以用列表推導做類似的事情:
if some_condition:
do this
else:
res = [x for x in list if x.method()]
if res:
do something to res[0]
else:
do something else
為避免對每個值執行x.method()
,您還可以使用itertools.dropwhile
。 以下方法將繼續檢查x.method()
直到找到一個為true,然后停止並返回x
值。 如果它沒有找到任何真實的東西,它將做其他事情。
from itertools import dropwhile
if some_condition:
do this
else:
try:
res = next(dropwhile(lambda x: not x.method(), x))
do something to res
except StopIteration:
do something else
只要您不需要在elif塊之外引用x,這就可以工作。 這感覺最接近你要求的語法,但我仍然可能會使用Kevin或Tobias的答案,因為它們更明確和可讀。
def check_and_do(x):
b = x.method()
if b:
do this to x
return b
if condition:
do this
elif any(check_and_do(x) for x in list):
pass # Already did this to x in check_and_do
else:
do something else
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.