• collection系列用法-namedtuple()


    namedtuple()

    参考文章地址:http://www.cnblogs.com/herbert/p/3468294.html

    namedtuple是继承自tuple的子类。namedtuple和tuple比,有更多更酷的特性。namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性。这对象更像带有数据属性的类,不过数据属性是只读的。

    实例如下:

    1 import  collections
    2 Mytuple=collections.namedtuple('Mytuple',['x','y'])
    3 n=Mytuple(1,2)
    4 print n.x
    5 1
    6 print n.y
    7 2
    8 print n
    9 Mytuple(x=1, y=2)
    namedtuple

    Mytuple = namedtuple('TPoint', ['x', 'y']) 创建一个Mytuple类型,而且带有属性x, y.

     来解释一下nametuple的几个参数:

    1 import collections  
    2 Person = collections.namedtuple('Person','name age gender')  
    3 print 'Type of Person:', type(Person)  
    4 Bob = Person(name='Bob', age=30, gender='male')  
    5 print 'Representation:', Bob  
    6 Jane = Person(name='Jane', age=29, gender='female')  
    7 print 'Field by Name:', Jane.name  
    8 for people in [Bob,Jane]:  
    9      print "%s is %d years old %s" % people
    example

    以Person = collections.namedtuple(‘Person’, 'name age gender’)为例,

    其中’Person’是这个namedtuple的名称,后面的’name age gender’这个字符串中三个用空格隔开的字符告诉我们,
    我们的这个namedtuple有三个元素,分别名为name, age和gender。
    我们在创建它的时候可以通过Bob = Person(name=’Bob’, age=30, gender=’male’)这种方式,这类似于Python中类对象的使用。
    而且,我们也可以像访问类对象的属性那样使用Jane.name这种方式访问namedtuple的元素。
    其输出结果如下:

    1 Type of Person: <type 'type'>  
    2 Representation: Person(name='Bob', age=30, gender='male')  
    3 Field by Name: Jane  
    4 Bob is 30 years old male  
    5 Jane is 29 years old female
    results

    几个重要的方法:

    1.把数据变成namedtuple类:

    Mytuple = namedtuple('Mytuple', ['x', 'y'])
    test= [11, 22]
    p = Mytuple ._make(test)
    p
    Mytuple (x=11, y=22)

    2. 根据namedtuple创建的类生成的类示例,其数据是只读的,如果要进行更新需要调用方法_replace.

     1 >>> p
     2 Mytuple(x=11, y=22)
     3 >>> p.x
     4 11
     5 >>> p.y
     6 22
     7 >>> p.y=33
     8 
     9 Traceback (most recent call last):
    10   File "<pyshell#16>", line 1, in <module>
    11     p.y=33
    12 AttributeError: can't set attribute
    13 >>> p._replace(y=33)
    14 Mytuple(x=11, y=33)
    15 >>> p
    16 Mytuple(x=11, y=22)
    17 >>> 

    3.将数据字典转化成namedtuple类型:注意一下p和dp是两个不同的实例,不要被都叫Mytuple给误导了!

    1 >>> d={'x':44,'y':55}
    2 >>> dp=Mytuple(**d)
    3 >>> dp
    4 Mytuple(x=44, y=55)
    5 >>> p
    6 Mytuple(x=11, y=22)

    4.namedtuple最常用还是出现在处理来csv或者数据库返回的数据上。利用map()函数和namedtuple建立类型的_make()方法

     1 EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
     2 
     3 import csv
     4 for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
     5     print(emp.name, emp.title)
     6 
     7 # sqlite数据库
     8 import sqlite3
     9 conn = sqlite3.connect('/companydata')
    10 cursor = conn.cursor()
    11 cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
    12 for emp in map(EmployeeRecord._make, cursor.fetchall()):
    13     print(emp.name, emp.title)
    14     
    15 # MySQL 数据库
    16 import mysql
    17 from mysql import connector
    18 from collections import namedtuple
    19 user = 'herbert'
    20 pwd = '######'
    21 host = '127.0.0.1'
    22 db = 'world'
    23 cnx = mysql.connector.connect(user=user, password=pwd, host=host,database=db)
    24 cur.execute("SELECT Name, CountryCode, District, Population FROM CITY where CountryCode = 'CHN' AND Population > 500000")
    25 CityRecord = namedtuple('City', 'Name, Country, Dsitrict, Population')
    26 for city in map(CityRecord._make, cur.fetchall()):
    27     print(city.Name, city.Population)
  • 相关阅读:
    CF1540B Tree Array
    CF1539F Strange Array
    CF526F Pudding Monsters
    怎样用 VS 2017 编译 cpprestsdk 库
    【转】C语言中常见的内存错误与解决方法
    vs2019 windbg方式远程调试应层程序
    关于 类似QQ 长截图的方案
    AIX小型机
    vSphere
    Git的使用
  • 原文地址:https://www.cnblogs.com/chushiyaoyue/p/5328224.html
Copyright © 2020-2023  润新知