defaultdict 和 namedtuple 的使用(python)

defaultdict  和 namedtuple 的使用

defaultdict()和namedtuple()是collections模块里面2个很实用的扩展类型。一个继承自dict系统内置类型,一个继承自tuple系统内置类型。在扩展的同时都添加了额外的很酷的特性,而且在特定的场合都很实用。

定义以及作用
返回一个和dictionary类似的对象,和dict不同主要体现在2个方面:

可以指定key对应的value的类型。
不必为默认值担心,换句话说就是不必担心有key没有value这回事。总会有默认的value.

d = defaultdict(list),该语句创建一个defaultdict类型(你可以想象为dict类型),value的类型是list。通过对d_3的对比就能看到,defaultdict是可以直接就进行d[k]的操作,即使d此时还是一个空的字典。实际过程就是示例里d_2的处理过程。

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

#coding:utf-8
from collections import namedtuple
from pprint import pformat    #这个库的效果是使格式化和print更美观(每行更容易看)

class Node(namedtuple('Node','pointData left right label')): #用Node来表示树的结构
#pointData是自己的值,left为左子树,right为右子树,label为该数据的类别
    def __repr__(self):       #使对于类Node的print会先用pformat进行美观格式化
        return pformat(tuple(self))

node = Node(10, None, None, 1)

# node = Node(pointData=10, left=None, right= None, label = 1)

# print node




from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

d = defaultdict(list)

for k, v in s:
    d[k].append(v)

d['red'] = [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] 


print defaultdict

print d.items(), d.keys()

# d_2 = {}

# for k, v in s:
#     d_2.setdefault(k, []).append(v)

# print(list(d_2.items()))

# d_3 = {}

# for k, v in s:
#     d_3[k].append(v)

# print(d_3.items())


f = dict()


几个重要的方法:

1.把数据变成namedtuple类:

>>> TPoint = namedtuple('TPoint', ['x', 'y'])
>>> t = [11, 22]
>>> p = TPoint._make(t)
>>> p
TPoint(x=11, y=22)
>>>

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

>>> p
TPoint(x=11, y=22)
>>> p.y
22
>>> p.y = 33
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    p.y = 33
AttributeError: can't set attribute
>>> p._replace(y=33)
TPoint(x=11, y=33)
>>> 

3.将字典数据转换成namedtuple类型。
>>> d = {'x': 44, 'y': 55}
>>> dp = TPoint(**d)
>>> dp
TPoint(x=44, y=55)
>>> 
 

namedtuple最常用还是出现在处理来csv或者数据库返回的数据上。利用map()函数和namedtuple建立类型的_make()方法。
>>> d = {'x': 44, 'y': 55}
>>> dp = TPoint(**d)
>>> dp
TPoint(x=44, y=55)
>>> 
 


# sqlite数据库
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)


# MySQL 数据库
import mysql
from mysql import connector
from collections import namedtuple
user = 'herbert'
pwd = '######'
host = '127.0.0.1'
db = 'world'
cnx = mysql.connector.connect(user=user, password=pwd, host=host,database=db)
cur.execute("SELECT Name, CountryCode, District, Population FROM CITY where CountryCode = 'CHN' AND Population > 500000")
CityRecord = namedtuple('City', 'Name, Country, Dsitrict, Population')
for city in map(CityRecord._make, cur.fetchall()):
    print(city.Name, city.Population)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章