为什么在ifelse表达式的第二个条件中尾随逗号会导致第一个条件强制转换为tup

2024-10-01 09:31:28 发布

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

用逗号声明元组的语法很清楚,我看到的每一处都是用大括号括起来的文字,例如(1,)。在

但是,python确实允许使用逗号而不使用括号来声明元组,并且在一个特定的情况下有奇怪的行为,请参阅下面的代码。在

def ifElseExpressionTrailingComma():
    return 1 if True else 0,

def ifElseExpressionTrailingCommaWrapped():
    return 1 if True else (0,)

print ifElseExpressionTrailingComma()
print ifElseExpressionTrailingCommaWrapped()

输出:

^{pr2}$

在2.7和3.5测试。 有人能解释为什么1隐式转换成元组吗?在


Tags: true声明returnifdef语法大括号else
2条回答

这是因为三元运算符(a if b else c)比“逗号”运算符强。

您可以将其与逻辑or和{}运算符进行比较,其中and强于or

if foo and bar or bats:

# means:
if (foo and bar) or bats:

这只是操作的顺序:

>>> 1 if True else 0,
(1,)
>>> (1 if True else 0),
(1,)
>>> 1 if True else (0,)
1

相关问题 更多 >