为什么单个元素元组被解释为python中的那个元素?

2022-01-19 00:00:00 python tuples printf convention

问题描述

谁能解释为什么单元素元组在 Python 中被解释为那个元素?

Could anyone explain why single element tuple is interpreted as that element in Python?

他们为什么不将元组 (1,) 打印为 (1)?

Why don't they just print the tuple (1,) as (1)?

请看下面的例子:

>>> (1)
1
>>> ((((1))))
1
>>> print(1,)
1
>>> print((1,))
(1,)


解决方案

单个元素元组永远不会被视为包含的元素.括号主要用于分组,而不是创建元组;逗号就是这样做的.

A single element tuple is never treated as the contained element. Parentheses are mostly useful for grouping, not for creating tuples; a comma does that.

他们为什么不直接将 (1,) 打印为 (1)?

Why don't they just print (1,) as (1)?

可能是因为打印内置容器类型提供了一种表示形式,可用于通过 重新创建容器对象,例如 eval:

Probably because printing a builtin container type gives a representation that can be used to recreate the container object via , say eval:

__repr__的文档a> 对此提供了一些说明:

The docs for __repr__ provides some clarity on this:

如果可能的话,这应该看起来像一个有效的 Python 表达式可用于重新创建具有相同值的对象

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value

回答您的问题,(1) 只是带有分组括号的整数 1.为了通过其表示重新创建单例元组,它必须打印为 (1,) 这是创建元组的有效语法.

Answering your question, (1) is just integer 1 with a grouping parenthesis. In order to recreate the singleton tuple via its representation, it has to be printed as (1,) which is the valid syntax for creating the tuple.

>>> t = '(1,)'
>>> i = '(1)'
>>> eval(t)
(1,) # tuple
>>> eval(i)
1    # int

相关文章