namedtuple类

导入模块

from collections import namedtuple

使用方法及说明

#pycharm 里按住 ctrl键点击 collections可查看源码

#collections数据结构
#__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList','UserString', 'Counter', 'OrderedDict', 'ChainMap']

使用说明:

#猜包功能
name = ("lijie",'ll')
user = ("aa",23,189,'boddy') username,age,height,edu = user
print (username,age,height,edu)

打印结果:
aa 23 189 boddy #另一种方法
username,*other = user
print (username,other)

打印结果:
aa [23, 189, 'boddy']

namedtuple

功能说明:

相当于创建一个类,并调用类的属性的值

#传统类的属性值调用
class User1(object):
def __init__(self,name,age,height):
self.name = name
self.age = age
self.height = height

常规操作
#使用namedtuple,namedtuple是tuple的子类,相比于class,节省空间,代码变少,使用方法如下:
User = namedtuple("user",['name','age','height'])    #相当于类的初始化,初始化变量信息
user = User(name='test',age=23,height=111)        #给各参数赋值
print (user.name,user.age,user.height)           #直接打印类的属性的值 #增加一列(*args方式,元组)
User = namedtuple("user",['name','age','height',"edu"])      #假如edu为新增加的列
user = ('test',23,111)   #元组
user_end = User(*user,"master") ##将数组传到namedtuple里,master为添加的edu的信息
print (user_end.name,user_end.age,user_end.height,user_end.edu) #以**kwargs的方式增加列或传入数据(字典)
User = namedtuple("user",['name','age','height',"edu"])
user = {                  #字典
"name":'test',
"age":23,
"height":111
}
user_end = User(**user,edu="master") ##将字典数据传到namedtuple里print (user_end.name,user_end.age,user_end.height,user_end.edu) #_make方法
##如果用_make方法,可以把“*”省略,但是要求tuple或者dict里的元素数量必须与nametuple里指定的属性数量相同,例:
user1 = {
"name":'test',
"age":23,
"height":111,
"edu":"aa"
}
user_end = User._make(user1)
print (user_end.name,....) #当然,namedtuple也支持猜包
name,age,*other = user_end
print (name,age,other)

额外补充

tuple 可作为字典的key,而list不可以,示例:

name_tuple = ("test",22,185,"baskerball")
name_list = ["test1",22,188,"baseball"] dd = {}
dd[name_tuple] = 'boddy'
print (dd) dd[name_list] = 'body'
print (dd)

打印结果: {('test', 22, 185, 'baskerball'): 'boddy'} Traceback (most recent call last):
File "D:/python-script/collections_module/chapter1/collection_module.py", line 29, in <module>
dd[name_list] = 'body'
TypeError: unhashable type: 'list'

collections 数据结构模块namedtuple的更多相关文章

  1. collections集合模块 [namedtuple,deque,*]

    collections是Python内建的一个集合模块,提供了许多有用的集合类. namedtuple namedtuple是一个函数, 它用来创建一个自定义的tuple对象,并且规定了 tuple元 ...

  2. collections模块-namedtuple

    namedtuple -> 命名元组 这里的命名指的是对元组中元素的命名. 通过一个例子来看 import collections Person = collections.namedtuple ...

  3. python基础 ---time,datetime,collections)--时间模块&collections 模块

    python中的time和datetime模块是时间方面的模块 time模块中时间表现的格式主要有三种: 1.timestamp:时间戳,时间戳表示的是从1970年1月1日00:00:00开始按秒计算 ...

  4. 25、typing导入Python的数据类型模块、collections集合模块

    一.typing模块 1.typing模块的作用 类型检查,防止运行时出现参数和返回值类型不符合. 作为开发文档附加说明,方便使用者调用时传入和返回参数类型. 该模块加入后并不会影响程序的运行,不会报 ...

  5. python基础语法12 内置模块 json,pickle,collections,openpyxl模块

    json模块 json模块: 是一个序列化模块. json: 是一个 “第三方” 的特殊数据格式. 可以将python数据类型 ----> json数据格式 ----> 字符串 ----& ...

  6. The Collections Module内建collections集合模块

    https://www.bilibili.com/video/av17396749/?p=12 Python函数式编程中的迭代器,生成器详解 课程内容 1.iterators are objects ...

  7. collections库的namedtuple+pytest的使用

    from collections import namedtupleTask=namedtuple('Task',['summary','owner','done','id'])Task.__new_ ...

  8. fis中的数据结构模块Config

    /* * config * caoke */ 'use strict'; Object.extend=function(props){ //继承父类 var prototype=Object.crea ...

  9. Python高级数据结构-Collections模块

    在Python数据类型方法精心整理,不必死记硬背,看看源码一切都有了之中,认识了python基本的数据类型和数据结构,现在认识一个高级的:Collections 这个模块对上面的数据结构做了封装,增加 ...

随机推荐

  1. 【C/C++】c文件重点总结

    c文件重点知识总结 程序文件数据文件--->分文本文件(ASCII文件)和映像文件(二进制文件) .区分是用记事本打开后能否看懂. 用二进制文件读写花费时间少,因为用文本文件需要有一个转换的过程 ...

  2. import logging报错raise notimplementederror 'emit must be implemented ' ^

    在导入logging的时候出现这个错误 大概看了一下,就是因为python内置里面已经有logging这个模块,所以不需要再安装 在site-packages里面找到关于logging的文件,删掉 重 ...

  3. linux-shell系列3-wafAPI

    #!/bin/bash datestr=`env LANG=en_US.UTF-8 date -u "+%a, %d %b %Y %H:%M:%S GMT"`pwdstr=`ech ...

  4. MySql 主从同步 (库名不同)

    主库:192.168.1.250 从库:192.168.1.199 主库  my.ini # For advice on how to change settings please see # htt ...

  5. python+appium里的等待时间

    为什么要用等待时间: 今天在写App的自动化的脚本时发现一个元素,时而能点击,时而又不能点击到,很是心塞,原因是:因为元素还没有被加载出来,查找的代码就已经被执行了,自然就找不到元素了.解决方式:可以 ...

  6. CCPC-Wannafly Winter Camp Day1 (Div2, onsite) A B C E F I J

    A 机器人 链接:https://www.cometoj.com/contest/7/problem/A?problem_id=92 思路: 分两大类讨论: 1. B区没有点: (1)点都在起点左边 ...

  7. RSS阅读器“阅读原文”报错400

    问题 使用SpringMVC框架,实现了RSS订阅,在FoxMail的RSS订阅页面,点击[阅读原文],报错400 . 每个RSS文章的链接是:https://jiashubing.cn/forum/ ...

  8. Log Parser Studio 分析 IIS 日志

    Log Parser Studio 分析 IIS 日志 来源 https://www.cnblogs.com/lonelyxmas/p/8671336.html 软件下载地址: Log Parser ...

  9. 【BZOJ5302】[HAOI2018]奇怪的背包(动态规划,容斥原理)

    [BZOJ5302][HAOI2018]奇怪的背包(动态规划,容斥原理) 题面 BZOJ 洛谷 题解 为啥泥萌做法和我都不一样啊 一个重量为\(V_i\)的物品,可以放出所有\(gcd(V_i,P)\ ...

  10. [SPOJ913]QTREE2 - Query on a tree II【倍增LCA】

    题目描述 [传送门] 题目大意 给一棵树,有两种操作: 求(u,v)路径的距离. 求以u为起点,v为终点的第k的节点. 分析 比较简单的倍增LCA模板题. 首先对于第一问,我们只需要预处理出根节点到各 ...