python中collections.namedtuple

 

'''
collections是Python内建的一个集合模块,提供了许多有用的集合类。

collections.namedtuple是一个工厂方法,它可以动态的创建一个继承tuple的子类。跟tuple相比,返回的子类可以使用名称来访问元素。

namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。

这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。
'''
from collections import namedtuple

# namedtuple('名称', [属性list]):
Circle_d = namedtuple('Circle', ['x', 'y', 'r'])

a=Circle_d(1,2,3)
print(a)
print(a.x)
print(a._replace(x = 5))

# result:
# Circle(x=1, y=2, r=3)
# 1
# Circle(x=5, y=2, r=3)

 下面官方的文档,我摘抄下来的

"""Returns a new subclass of tuple with named fields."""

Point = namedtuple('Point', ['x', 'y'])
print(Point.__doc__)              # docstring for the new class)
# Point(x, y)
p = Point(11, y=22)             # instantiate with positional args or keywords
print(p[0] + p[1])                     # indexable like a plain tuple
# 33
x, y = p                        # unpack like a regular tuple
print(x, y)
# (11, 22)
print(p.x + p.y)                       # fields also accessible by name
# 33
print(p._replace(x=100))               # _replace() is like str.replace() but targets named fields
# Point(x=100, y=22)


d = p._asdict()                 # convert to a dictionary
print(d)
print(d['x'])
# 11

print(Point(**d)[1])                      # convert from a dictionary
# Point(x=11, y=22)

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值