有没有更多的方法来定义只有一个项目的元组?

Alp*_*nse 7 python singleton tuples

我知道这是一种方式,通过放置一个逗号:

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Run Code Online (Sandbox Code Playgroud)

资料来源:http://docs.python.org/tutorial/datastructures.html

是否有更多方法来定义仅有1个项目的元组?

Jos*_*Lee 11

>>> tuple(['hello'])
('hello',)
Run Code Online (Sandbox Code Playgroud)

但是内置语法是有原因的.

  • @Edan:使用内置的代码较少,但是尾随的逗号并没有真正地说出"TUPLE!"......我的眼睛可能会错过它. (3认同)

awe*_*omo 5

即使您可以定义一个元组,因为'hello',我认为如果有人正在阅读您的代码,他们很容易错过尾随的逗号。('hello',)从可读性的角度来看,我绝对更喜欢 。