下面的代码没有打印出我所期望的:
#!/usr/bin/env python
print type(1,)
a = 1,
print type(a)
这是输出:
<type 'int'>
<type 'tuple'>
我知道逗号使 a 变成了元组。但如果是这样的话,为什么原始打印不是打印元组类型而是打印整数呢?
最佳答案
因为函数调用中的元组语法也是传递参数的方式:
>>> print type(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type() takes 1 or 3 arguments
>>> print type((1,))
<type 'tuple'>
>>> a = 1,
>>> type(a)
<type 'tuple'>
这是 python 的语法歧义,它通过确定您正在尝试传递参数来解决(如果您问我,这应该是语法错误)。
>>> print type(1,)
>>> print type(1)
相同。
关于python - 是什么构成了 python 元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6007728/