python里如何调用namedtuple里的数值_python 2-2 如何为元组中的每个元素命名, 提高程序可读性-collections.namedtuple...

from collections import namedtuple

Person = namedtuple('Person',['name','age','sex','email'])

person1 = Person("xiaowang",55,1,'xiaowang@126.com')

print person1.email

import collections

dir(collections)

['Callable', 'Container', 'Counter', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView', 'Mapping', 'MappingView', 'MutableMapping', 'MutableSequence', 'MutableSet', 'OrderedDict', 'Sequence', 'Set', 'Sized', 'ValuesView', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_abcoll', '_chain', '_get_ident', '_heapq', '_iskeyword', '_itemgetter', '_repeat', '_starmap', '_sys', 'defaultdict', 'deque', 'namedtuple']

>>>

>>>help(collections.namedtuple)

Help on function namedtuple in module collections:

namedtuple(typename, field_names, verbose=False, rename=False)

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 accessable 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)

def namedtuple(typename, field_names, verbose=False, rename=False):

"""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 accessable 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值