[英]Inconsistency in printing tuples in python
I have just started to learn python and following the docs on tuples, I came across this snippet,我刚刚开始学习 python 并遵循元组上的文档,我遇到了这个片段,
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Following this I ran following snippet,在此之后,我运行了以下代码段,
>>> foo=1,2,3,
>>> len(foo)
3
>>> foo
(1, 2, 3)
Why does singleton
prints with an trailing comma ,
where as foo
seems to trim it ?为什么
singleton
打印带有尾随逗号,
而foo
似乎修剪了它?
Beacause ("Hello")
is not a tuple, it is same as "Hello"
.因为
("Hello")
不是元组,它与"Hello"
相同。
>>> ("Hello")
'Hello'
in order to distinguish tuple
with single element from a simple expression in ()
a ,
is necessary.为了将具有单个元素的
tuple
与()
a 中的简单表达式区分开来,
是必要的。 Whereas (1,2,3)
is clearly a collection of items, and as they are enclosed by ()
it can easily be inferred as a tuple
, hence no need for a trailing ,
.而
(1,2,3)
显然是一个项的集合,并且由于它们被()
包围,因此可以很容易地将其推断为tuple
,因此不需要尾随,
。
因为你将变量“singleton”定义为 ("hello",),你不需要逗号来结束它,而对于“foo”,你定义了它,所以它显示为你定义的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.