【Python】06、python内置数据结构之列表和元祖
In : t = ("xxj", 18)In : t
Out: ('xxj', 18)
In : t
Out: 'xxj'
In : t
Out: 18
In : from collections import namedtuple # 导入collectons模块的namedtuple类
In : User = namedtuple('_Yonghu', ["name", "age"])# 类初始化
In : User
Out: __main__._Yonghu
In : me = User("xxj", 18)
In : me
Out: _Yonghu(name='xxj', age=18)
In : me.name
Out: 'xxj'
In : me.name()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-243-658c183ca1b1> in <module>()
----> 1 me.name()
TypeError: 'str' object is not callable
In : me.age
Out: 18
In : me
Out: 'xxj'
In : me
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-246-4bc5e7d46893> in <module>()
----> 1 me
IndexError: tuple index out of range
In : me = "xj"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-247-627de02ba5b9> in <module>()
----> 1 me = "xj"
TypeError: '_Yonghu' object does not support item assignment
In : type(namedtuple)
Out: function
In : type(User)
Out: type
In : type(me)
Out: __main__._Yonghu
In : print(namedtuple.__doc__)
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 + p # 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
页:
[1]