前段时间我以为元组的构造函数是一对括号()
。为什么在元组中需要括号?
例子:
>>> (1,)
(1,)
>>> type((1,))
<type 'tuple'>
>>> t = (1,)
>>> type(t)
<type 'tuple'>
但现在我知道,这是逗号,
。
所以,做与上面相同:
>>> 1,
(1,)
>>> type(1,)
<type 'int'> # Why?
>>> 1,2,3
(1,2,3)
但是,如果我做的:
>>> type(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type() argument 1 must be string, not int
这对我来说很有意义,但是:
>>> t = 1,2,3
>>> type(t)
<type 'tuple'>
最后:
>>> type((1,2,3))
<type 'tuple'>
下面是一个问题:如果元组只是1,2,3
,为什么在最后一种情况下需要括号?
类型(1,2,3)可能会混淆python,因为','用于分隔参数。所以它可能会认为1是第一个参数,2是第二个参数等等。 – NendoTaka
https://stackoverflow.com/questions/16017811/when-are-parentheses-required-around-a-tuple – chishaku
'type(())'怎么样?这返回'tuple'。 –