列表理解支持if
但不else
因爲if
部分過濾器元素,你要麼包含一個元素,或者你不包括它,一個布爾值的選擇。
如果你想利用條件表達式來構建for
循環,使用括號的迭代部分:
return [tower for tower in (state if tower != space else [])]
但我懷疑你想改變的表達在價值代替元素表達式;這不是過濾,你只是爲某些項目產生不同的值。使用conditional expression出示你的價值觀:
return [tower if tower != space else [] for tower in state]
,或者如果你真的想要進行篩選,簡單地忽略else
:
return [tower for tower in state if tower != space]
當構建一個列表理解,記住,你需要閱讀表達嵌套從左至右,最後表達產生結果出左側:
[element_producing_expression for name in iterable if filter_expression]
是道德等價的:
for name in iterable:
if filter_expression:
element_producing_expression
在那裏你可以使用盡可能多的嵌套循環和if
過濾器爲您的使用案例需要。
我上述三個選項然後像:
# conditional expression producing the iterable
for tower in (state if tower != space else []):
tower
# conditional expression in the element expression
for tower in state:
tower if tower != space else []
# filtering expression with no else
for tower in state:
if tower != space:
tower