在命名元组里。给每一个元组的位置加入一个名称,而且能够通过名称来訪问。大大地提高可读性,以便写出清晰代码,提高代码的维护性。事实上它就像C++里的结构体。

collections.namedtuple(typename, field_names, verbose=False, rename=False)

返回一个新类型名称typenname的元组。參数field_names是一个字串表示的元素名称,每一个字段之间能够通过空格、逗号方式来分隔,比方’x y’,’x, y’。

另外也能够採用列表的方式,比方[‘x’, ‘y’]。在字段名称命名上须要注意的是每一个字段要是有效的python标识符规则,同一时候不能是pythonkeyword。另外不要下面划线或数字开头。

假设參数rename为True就会自己主动地把不合法名称转换为对应合法的名称,比方:['abc', 'def', 'ghi', 'abc']转换为['abc', '_1', 'ghi', '_3'],在这里把def转换_1,同一时候把反复的abc转换_3。

假设參数verbose为True就会自己主动打印_source属性。

样例:

#python 3.4

import collections

Point = collections.namedtuple('Point', 'x, y, z')

p1 = Point(30, 40, 50)

print(p1)

print(p1[0] + p1[1] + p1[2])

x, y, z = p1

print(x, y, z)

print(p1.x, p1.y, p1.z)

结果输出例如以下:

Point(x=30, y=40, z=50)

120

30 40 50

30 40 50

classmethod somenamedtuple._make(iterable)

从已经存在迭代对象或者序列生成一个新的命名元组。

样例:

#python 3.4

import collections

Point = collections.namedtuple('Point', 'x, y, z')

t = [10, 20, 30]

p1 = Point._make(t)

print(p1)

结果输出例如以下:

Point(x=10, y=20, z=30)

somenamedtuple._asdict()

把命名元组生成一个新的OrderedDict对象返回,能够使用内置函数vars()实现对应的功能。

样例:

#python 3.4

import collections

Point = collections.namedtuple('Point', 'x, y, z')

t = [10, 20, 30]

p1 = Point._make(t)

print(p1._asdict())

print(vars(p1))

结果输出例如以下:

OrderedDict([('x', 10), ('y', 20), ('z', 30)])

OrderedDict([('x', 10), ('y', 20), ('z', 30)])

somenamedtuple._replace(kwargs)

对指定的字段的值进行替换。并返回新的命名元组。

样例:

#python 3.4

import collections

Point = collections.namedtuple('Point', 'x, y, z')

t = [10, 20, 30]

p1 = Point._make(t)

print(p1._replace(x=100))

print(vars(p1))

结果输出例如以下:

Point(x=100, y=20, z=30)

OrderedDict([('x', 10), ('y', 20), ('z', 30)])

somenamedtuple._source

返回创建命名元组相关的python代码字符串。能够把它打印出来,或者使用exec()函数运行。或者输出到文件中,再给别的代码导入。

样例:

#python 3.4

import collections

Point = collections.namedtuple('Point', 'x, y, z')

t = [10, 20, 30]

p1 = Point._make(t)

print(p1._source)

输出结果例如以下:

from builtins import property as _property, tuple as _tuple

from operator import itemgetter as _itemgetter

from collections import OrderedDict

class Point(tuple):

'Point(x, y, z)'

__slots__ = ()

_fields = ('x', 'y', 'z')

def __new__(_cls, x, y, z):

'Create new instance of Point(x, y, z)'

return _tuple.__new__(_cls, (x, y, z))

@classmethod

def _make(cls, iterable, new=tuple.__new__, len=len):

'Make a new Point object from a sequence or iterable'

result = new(cls, iterable)

if len(result) != 3:

raise TypeError('Expected 3 arguments, got %d' % len(result))

return result

def _replace(_self, **kwds):

'Return a new Point object replacing specified fields with new values'

result = _self._make(map(kwds.pop, ('x', 'y', 'z'), _self))

if kwds:

raise ValueError('Got unexpected field names: %r' % list(kwds))

return result

def __repr__(self):

'Return a nicely formatted representation string'

return self.__class__.__name__ + '(x=%r, y=%r, z=%r)' % self

@property

def __dict__(self):

'A new OrderedDict mapping field names to their values'

return OrderedDict(zip(self._fields, self))

def _asdict(self):

'Return a new OrderedDict which maps field names to their values.'

return self.__dict__

def __getnewargs__(self):

'Return self as a plain tuple.  Used by copy and pickle.'

return tuple(self)

def __getstate__(self):

'Exclude the OrderedDict from pickling'

return None

x = _property(_itemgetter(0), doc='Alias for field number 0')

y = _property(_itemgetter(1), doc='Alias for field number 1')

z = _property(_itemgetter(2), doc='Alias for field number 2')

somenamedtuple._fields

返回命名元组的字段列表。

能够用于从已经创建命名元组组合产生新的元组。

样例:

#python 3.4

import collections

Point = collections.namedtuple('Point', 'x, y, z')

print(Point._fields)

Point4 = collections.namedtuple('Point4', Point._fields + ('w',))

print(Point4, Point4._fields)

结果输出例如以下:

('x', 'y', 'z')

<class '__main__.Point4'> ('x', 'y', 'z', 'w')

使用命名元组从csv文件或者SQLite生成结构体信息保存:

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv

for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):

print(emp.name, emp.title)

import sqlite3

conn = sqlite3.connect('/companydata')

cursor = conn.cursor()

cursor.execute('SELECT name, age, title, department, paygrade FROM employees')

for emp in map(EmployeeRecord._make, cursor.fetchall()):

print(emp.name, emp.title)

从这个样例里。能够看到从csv文件读取之后。就能够函数map的运算。生成一个EmployeeRecord结构体记录了,这样能够把行记录转换对应的结构化的信息。就方便查找,排序等操作。

使用命名元组作为基类继承:

#python 3.4

import collections

class Point(collections.namedtuple('Point', 'x y')):

__slots__ = ()

@property

def hypot(self):

return (self.x ** 2 + self.y ** 2) ** 0.5

def __str__(self):

return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)

for p in Point(3, 4), Point(14, 5/7):

print(p)

结果输出例如以下:

Point: x= 3.000  y= 4.000  hypot= 5.000

Point: x=14.000  y= 0.714  hypot=14.018

蔡军生 QQ:9073204 深圳

5.3.5 namedtuple() 创建命名字段的元组结构的更多相关文章

  1. mysql必知必会--创建计算字段

    计算字段 存储在数据库表中的数据一般不是应用程序所需要的格式.下面举 几个例子. * 如果想在一个字段中既显示公司名,又显示公司的地址,但这两 个信息一般包含在不同的表列中. * 城市.州和邮政编码存 ...

  2. sqlServer 2008修改字段类型和重命名字段名称的sql语句

    sqlServer 2008修改字段类型和重命名字段名称的sql语句 //修改字段的类型 alter table fdi_news alter column c_author nvarchar(50) ...

  3. Hibernate 注解 没有加@Column一样会在数据库创建这些字段

    Hibernate 注解 没有加@Column一样会在数据库创建这些字段 如下一个注解类: package com.hyy.hibernate.one_to_many.domain; import j ...

  4. Django之集合函数使用与mysql表的创建特殊字段分析

    1. 集合函数的使用场景: -- 单独使用: 不分组, 只查聚合结果 -- 分组使用: 按字段分组, 可查询分组字段与聚合结果 2. 导入聚合函数 from django.db.models impo ...

  5. JavaScript 如何创建search字段

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. SAP不同的产品是如何支持用户创建自定义字段的

    我们从SAP CRM,Cloud for Customer(简称C4C)和S/4HANA这三个产品分别来看看. SAP CRM 我们使用所谓的Application Enhancement Tool( ...

  7. SAP abap 内表增加字段方法,结构复用

    1.include data: begin of gth_qamr.         include structure qamr. data: kurztext like qamv-kurztext ...

  8. maven系列之二maven项目的创建和maven项目的结构

    maven系列之一简单介绍了maven的基本信息,安装和配置,大家对maven有一个大概的了解,但是在maven项目开发中远远不够,为了进一步了解maven,现在我们介绍maven项目的创建和mave ...

  9. linux mysql-workbench 创建与正式库表结构一样的表

    先在本地创建数据库 字符集选择这个 创建数据库成功 创建与正式库一样的表 step1: 连接正式库,找到要生成的表,导出创建表的sql语句 step2: 找到本地数据库,选择表,在sql执行区域复制s ...

随机推荐

  1. 如何打开WCF测试客户端

  2. 编程算法 - 求1+2+...+n(模板类) 代码(C++)

    求1+2+...+n(模板类) 代码(C++) 本文地址: http://blog.csdn.net/caroline_wendy 题目: 求1+2+...+n, 要求不能使用乘除法\for\whil ...

  3. 小米2S电池电量用尽充电无法开机解决方法

    背景:        昨晚睡觉前关机,记得电量还有百分之七八十,但早上起床后,指示灯一直红灯闪烁.按开机键和其它键都没反应! ! 解决方法:         扣下电池,用万能充冲电,略微多冲一会,由于 ...

  4. 图像滤镜艺术---保留细节的磨皮之C#程序实现

    上一篇博文"保留细节的磨皮滤镜之PS实现"一文中.我简介了本人自己总结的一种非常easy的磨皮滤镜,这个滤镜在磨光皮肤的同一时候,会保留非常不错的细节,今天,我将介绍使用C#程序实 ...

  5. HDU 2732 Leapin&#39; Lizards(拆点+最大流)

    HDU 2732 Leapin' Lizards 题目链接 题意:有一些蜥蜴在一个迷宫里面,有一个跳跃力表示能跳到多远的柱子,然后每根柱子最多被跳一定次数,求这些蜥蜴还有多少是不管怎样都逃不出来的. ...

  6. java里面包的重要性-管理类文件

    包的必要性 包是用来给java源文件分门别类的,java中一个包在windows下就是一个文件夹.包的全限定名是从根文件夹開始的(\src文件夹)以点号作为分隔符,包名和包名之间使用点号隔开,java ...

  7. MongodDB用GridFS方式存取文件

    在实现GridFS方式前我先讲讲它的原理,为什么可以存大文件.驱动首先会在当前数据库创建两个集合:"fs.files"和"fs.chunks"集合,前者记录了文 ...

  8. angularjs1- ng-include

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  9. Ubuntu(64位)编译Android源码常见错误解决办法

    2013年07月10日 14:47:27 阅读数:1239 错误: /usr/include/gnu/stubs.h:7:27: error: gnu/stubs-32.h: No such file ...

  10. Spark RDD概念学习系列之Pair RDD的分区控制

    不多说,直接上干货! Pair RDD的分区控制 Pair RDD的分区控制 (1) Spark 中所有的键值对RDD 都可以进行分区控制---自定义分区 (2)自定义分区的好处:  1) 避免数据倾 ...