2014-03-27 19 views
3

我感到困惑的蟒蛇访问在namedtuple元素,说我有如何在python中访问nametuples中的元素?

Container = namedtuple('Container', ('mac_0', 'mac_1')) 

我可以使用Container[0]Container[1]访问的第一个元素mac_0和第二个元素mac_1 ?

+0

[The docs](http://docs.python.org/2/library/collections.html#collectio ns.namedtuple)说它非常接近。 'c = Container(mac_0 = true,mac_1 = false)'然后'c [0]'等或者'c.mac_0' – wspurgin

回答

5

您可以访问元素按指数或按名称(documentation):

>>> from collections import namedtuple 
>>> Container = namedtuple('Container', ('mac_0', 'mac_1')) 
>>> container = Container(mac_0=1, mac_1=2) 
>>> container[0] 
1 
>>> container[1] 
2 
>>> container.mac_0 
1 
>>> container.mac_1 
2