博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python_collections_namedtuple可命名元组
阅读量:7239 次
发布时间:2019-06-29

本文共 844 字,大约阅读时间需要 2 分钟。

namedtuple:用来构建带字段名的元组

import collections# 创建类,两种创建方法MytupleClass = collections.namedtuple('MytupleClass', 'x y z')# MytupleClass = collections.namedtuple('MytupleClass',[ 'x', 'y', 'z'])obj = MytupleClass(11, 22, 33)      # 相当于创建了一个obj对象 x=11, y=22, z=33print(obj.x)print(obj.y)print(obj.z)

结果:

112233

类._make([ ]):用列表的形式创建对象

import collectionsMytupleClass = collections.namedtuple('MytupleClass',[ 'x', 'y', 'z'])new = MytupleClass._make([11, 22, 44])print(new)

结果:

MytupleClass(x=11, y=22, z=44)

x._replace():替换对象

x._asdict():转换为字典

import collectionsMytupleClass = collections.namedtuple('MytupleClass',[ 'x', 'y', 'z'])new = MytupleClass._make([11, 22, 44])new = new._replace(z=9)print(new) print(new.asdict())

结果:

MytupleClass(x=11, y=22, z=9) OrderedDict([('x', 11), ('y', 22), ('z', 9)])

 

转载于:https://www.cnblogs.com/Vera-y/p/9590816.html

你可能感兴趣的文章
[题解]Codeforces Round #254 (Div. 2) B - DZY Loves Chemistry
查看>>
imap以用户定义的方式导入自定义邮箱
查看>>
js中问号
查看>>
[原]回调实现步骤
查看>>
var img = new Image()
查看>>
linux每日命令(37):top命令
查看>>
【bzoj3811】【清华集训2014】玛里苟斯
查看>>
正则表达式
查看>>
自动ftp 上传
查看>>
C++命名法则
查看>>
MYSQL、ORACLE、SQLSERVER获取行号,增量查询
查看>>
Linux设备树语法详解
查看>>
读书笔记1——计算机编程艺术
查看>>
WPF 中使用行为示例——Canvas控件拖放行为的演示
查看>>
Java编程——列出目录下的文件
查看>>
开发该选择Blocks还是Delegates
查看>>
iOS-开发中的时间处理
查看>>
IOS willMoveToParentViewController和didMoveToParentViewController的使用
查看>>
微信小程序下拉框
查看>>
【Java】Swagger2 结合spring boot 请求接口自动生成文档
查看>>