Python中的元组声明 [英] Tuple declaration in Python
问题描述
在python中,可以这样显式地声明一个带有括号的元组:
In python, one can declare a tuple explicitly with parenthesis as such:
>>> x = (0.25, 0.25, 0.25, 0.25)
>>> x
(0.25, 0.25, 0.25, 0.25)
>>> type(x)
<type 'tuple'>
或者,不带括号,python自动将其打包成一个不可变的元组:
Alternatively, without parenthesis, python automatically packs its into a immutable tuple:
>>> x = 0.25, 0.25, 0.25, 0.25
>>> x
(0.25, 0.25, 0.25, 0.25)
>>> type(x)
<type 'tuple'>
是否存在用于声明元组的pythonic样式?如果是,请同时参考相关的PEP或链接.
Is there a pythonic style to declare a tuple? If so, please also reference the relevant PEP or link.
实现元组的最终产品"没有区别,但是在带括号和不带括号的元组的初始化方式(在CPython中)是否有区别?
There's no difference in the "end-product" of achieving the tuple but is there a difference in how the tuple with and without parenthesis are initialized (in CPython)?
推荐答案
从实际的角度来看,最好始终使用括号,因为它有助于提高代码的可读性.正如 import之一所说:
From practical point of view it's best to always use parenthesis as it contributes to readability of your code. As one of the import this
moto says:
显式比隐式更好."
"Explicit is better then implicit."
还请记住,在定义一个元组时,您需要使用逗号: one_tuple =(15,)
.
Also remember, that when defining one-tuple you need a comma: one_tuple = (15, )
.
这篇关于Python中的元组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!