在python三元组中使用continue?

时间:2014-01-21 11:58:22

标签: python conditional-statements continue ternary

如何在python三元组中使用continue?这甚至可能吗?

E.g。

>>> for i in range(10):
...     x = i if i == 5 else continue

提供SyntaxError: invalid syntax

如果可以继续使用三元组,还有其他方法可以做到这一点:

>>> for i in range(10):
...     if i ==5:
...             x = i #actually i need to run a function given some condition(s)
...     else:
...             continue
... 
>>> x
5

1 个答案:

答案 0 :(得分:10)

你不能; continue是一个语句,条件表达式是一个表达式,您不能在表达式中使用语句。毕竟,continue语句不会为要返回的条件表达式生成值。

使用if 语句代替:

if i == 5:
    x = i
else:
    continue

或更好:

if i != 5:
    continue
x = i