Vla*_*hka 1 python syntax if-statement tuples
使用逗号声明元组的语法是清楚的,我看到它的任何地方都使用括在括号中的文字,例如(1,).
但是,python允许使用逗号而不用括号来声明元组,并且在一个特定情况下有奇怪的行为,请参阅下面的代码.
def ifElseExpressionTrailingComma():
return 1 if True else 0,
def ifElseExpressionTrailingCommaWrapped():
return 1 if True else (0,)
print ifElseExpressionTrailingComma()
print ifElseExpressionTrailingCommaWrapped()
Run Code Online (Sandbox Code Playgroud)
输出:
(1,) # what??
1
Run Code Online (Sandbox Code Playgroud)
测试2.7和3.5.有人可以解释为什么1被隐式转换为元组吗?
这只是操作的顺序:
>>> 1 if True else 0,
(1,)
>>> (1 if True else 0),
(1,)
>>> 1 if True else (0,)
1
Run Code Online (Sandbox Code Playgroud)