Skip to main content
 首页 » 编程设计

python之我可以在 Python 的一行中写一个 if else 语句吗

2025年05月04日10telwanggs

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

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

请您参考如下方法:

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

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

对于 Python 3.2+ :

return x in {'A', 'B', 'C'} 

来自 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.