python模塊collections中namedtuple()的理解



from collections import namedtuple


'''
namedtuple是繼承自tuple的子類。namedtuple創建一個和tuple類似的對象,而且對象擁有可訪問的屬性。

Python中存儲系列數據,比較常見的數據類型有list,除此之外,還有tuple數據類型。
相比與list,tuple中的元素不可修改,在映射中可以當鍵使用。tuple元組的item只能通過index訪問,
collections模塊的namedtuple子類不僅可以使用item的index訪問item,還可以通過item的name進行訪問。
可以將namedtuple理解爲c中的struct結構,其首先將各個item命名,然後對每個item賦予數據。
'''

coordinate = namedtuple('Coordinate', ['x', 'y'])
co = coordinate(10,20)
print(co.x,co.y)
print(co[0],co[1])
co = coordinate._make([100,200])
print(co.x,co.y)
co = co._replace(x = 30)
print(co.x,co.y)
'''
10 20
10 20
100 200
30 200
'''

websites = [
    ('Sohu', 'http://www.google.com/', u'張朝陽'),
    ('Sina', 'http://www.sina.com.cn/', u'王志東'),
    ('163', 'http://www.163.com/', u'丁磊')
]

Website = namedtuple('Website', ['name', 'url', 'founder'])

for website in websites:
    website = Website._make(website)
    print(website)

 

from collections import namedtuple

# 定義一個namedtuple類型User,幷包含name,sex和age屬性。
User = namedtuple('User', ['name', 'sex', 'age'])

# 創建一個User對象
user = User(name='kongxx', sex='male', age=21)

# 也可以通過一個list來創建一個User對象,這裏注意需要使用"_make"方法
user = User._make(['kongxx', 'male', 21])

print user
# User(name='user1', sex='male', age=21)

# 獲取用戶的屬性
print user.name
print user.sex
print user.age

# 修改對象屬性,注意要使用"_replace"方法
user = user._replace(age=22)
print user
# User(name='user1', sex='male', age=21)

# 將User對象轉換成字典,注意要使用"_asdict"
print user._asdict()
# OrderedDict([('name', 'kongxx'), ('sex', 'male'), ('age', 22)])

本文地址:http://blog.csdn.net/kongxx/article/details/51553362

 

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