在 python 2 中将列表转换为元组时,我注意到将具有单个项目的任何列表转换为元组会在项目后产生一个逗号。
>>> tuple([0])
(0,)
>>> tuple(['i'])
('i',)
显示逗号的原因是什么?
它会导致除打印方式之外的任何意外行为吗?
我还注意到必须用逗号声明单个元组。
>>> (0)
0
>>> (0,)
(0,)
大概这是为了做出这样的表达
>>> 5 * (2 + 3)
25
代替
>>> 5 * (2 + 3)
(5, 5, 5, 5, 5)
请您参考如下方法:
这样输出就是对象的有效 Python 表示,这就是 repr 应该产生的结果。 (在元组的情况下,str 与 repr 相同,因为没有令人信服的理由使它们不同。)结尾的逗号是必需的,否则它实际上不是一个元组的表示。
来自关于 repr 的 Python 文档:
Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.
>>> eval(repr(tuple([0])))
(0,)
如果没有产生逗号,这将不成立。
