python tuple 一个元素时需要增加逗号

项目中使用python tuple时如果是一个元素一定要增加一个逗号,使用python3看下输出。

>>> t(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
>>> t=(0)
>>> print(type(t))
<class 'int'>
>>> print(t)
0
>>> t=(0,)
>>> print(type(t))
<class 'tuple'>
>>> print(t)
(0,)

 

官方文档中描述:

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, f(a, b, c) is a function call with three arguments, while f((a, b, c)) is a function call with a 3-tuple as the sole argument.

也就是元组的()并不是必须的,逗号才是, 增加()是为了再某些场景下发生歧异。

>>> t = 1,2,3
>>> print(type(t))
<class 'tuple'>
>>> print(t)
(1, 2, 3)

>>> t=1,
>>> print(type(t))
<class 'tuple'>
>>> print(t)
(1,)

可以看到没有增加(),t仍然被解释为tuple

空元组是个例外,还是需要()

>>> t=()
>>> print(type(t))
<class 'tuple'>
>>> print(t)
()

 

参考及引用

https://note.nkmk.me/en/python-tuple-single-empty/

图片fromNX Aung

Comments are closed.