我可以用Python在一行中编写if-else语句吗?

2024-03-27 11:00:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我不是说三元运算符。我可以在值表达式之外的一行中写if-else语句吗?我想缩短代码。在

if x == 'A':
    return True
if x == 'B':
    return True
if x == 'C':
    return True
return False

Tags: 代码falsetruereturnif表达式运算符语句
3条回答

您可以像这样使用in运算符:

return x in ('A', 'B', 'C')

对于Python 3.2+

^{pr2}$

docs

Python’s peephole optimizer now recognizes patterns such x in {1, 2, 3} as being a test for membership in a set of constants. The optimizer recasts the set as a frozenset and stores the pre-built constant.

Now that the speed penalty is gone, it is practical to start writing membership tests using set-notation.

如果检查比集合中的成员身份更复杂,并且希望减少代码行数,可以使用conditional expressions

return True if x == 'A' else True if x == 'B' else True if x == 'C' else False

您可以使用^{}来缩短代码:

return x in ("A", "B", "C")

或者,如果x是单个字符:

^{pr2}$

相关问题 更多 >