用逗号声明元组的语法很清楚,我看到的每一处都是用大括号括起来的文字,例如(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隐式转换成元组吗?在
这是因为三元运算符(
a if b else c
)比“逗号”运算符强。您可以将其与逻辑}运算符进行比较,其中
or
和{and
强于or
:这只是操作的顺序:
相关问题 更多 >
编程相关推荐