python - 在 Python 中替换三元运算符的最佳方法是什么?

标签 python

<分区>

Possible Duplicate:
Ternary conditional operator in Python

如果我有这样的代码:

x = foo ? 1 : 2

我应该如何将它翻译成 Python?我可以这样做吗?

if foo:
  x = 1
else:
  x = 2

x 还会在 if/then block 之外的范围内吗?或者我必须做这样的事情吗?

x = None
if foo:
  x = 1
else:
  x = 2

最佳答案

在 Python 2.5+ 中使用三元运算符(正式形式为 conditional expression)。

x = 1 if foo else 2

关于python - 在 Python 中替换三元运算符的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/643983/

相关文章:

python - 从列表中找到最接近的值?

Python:循环并编辑字符串字符

python - 错误栏帽的线条样式

python - Django 中的对象级级联权限

python - 如何检测我的 python 代码?

python - pd.to_datetime 返回一个对象,而不是时间序列

python - 为什么 'WriteOnlyWorksheet' 对象没有属性 'cell' ?

python - 编写 csv 输出 python

python - 用 Python 解析古腾堡的 RDF

python - “用户”对象没有属性 'is_verified'