如何在python中访问nametuples中的元素?
问题描述:
我感到困惑的蟒蛇访问在namedtuple
元素,说我有如何在python中访问nametuples中的元素?
Container = namedtuple('Container', ('mac_0', 'mac_1'))
我可以使用Container[0]
和Container[1]
访问的第一个元素mac_0
和第二个元素mac_1 ?
答
您可以访问元素按指数或按名称(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
[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