定义元组
>>> a = () #定义元组a
>>> b = (1, 2, 3, 4, 5) #定义元组b
>>> c = ('Hi', 'python', '!') #定义元组c
>>> d = ('Tom', 20, 'Jack', 19) #定义元组d
>>> print(a,b,c,d) #打印元组a,b,c,d
() (1, 2, 3, 4, 5) ('Hi', 'python', '!') ('Tom', 20, 'Jack', 19)
上面例子中的a是一个空的元组,与定义空列表差不多,直接使用a = ()就能将一个空的元组赋值给a。
需要注意的是,由于元组使用的是小括号,在数学中,有时候需要使用小括号来指定计算顺序,例如(2+3)/5,这时候优先计算2+3,然后再除以5。在python中,小括号同样指定计算顺序,在定义只有一个元素的元组时就会产生歧义。因此,使用以下方法定义一个只含有一个元素的元组。
>>> a = (1,) #定义元组a
>>> b = ('Tom',) #定义元组b
>>> c = (1) #定义c
>>> d = ('Tom') #定义d
>>> print(type(a)) #打印a的类型
<class 'tuple'>
>>> print(type(b)) #打印b的类型
<class 'tuple'>
>>> print(type(c)) #打印c的类型
<class 'int'>
>>> print(type(d)) #打印d的类型
<class 'str'>
namedtuple
Python的Collections模块提供了不少好用的数据容器类型,其中一个精品当属namedtuple。
namedtuple能够用来创建类似于元祖的数据类型,除了能够用索引来访问数据,能够迭代,更能够方便的通过属性名来访问数据。
源码:
def namedtuple(typename, field_names, *, verbose=False, rename=False, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""