为什么在Python中将单个元素元组解释为该元素? [英] Why single element tuple is interpreted as that element in python?
问题描述
有人可以解释为什么在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 __
为此提供了一些清晰度:
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
这篇关于为什么在Python中将单个元素元组解释为该元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!