Python的collections之namedtuple的使用及其优势
生活随笔
收集整理的這篇文章主要介紹了
Python的collections之namedtuple的使用及其优势
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
類實現(xiàn):
class User:def __init__(self, name, age, height):self.name = nameself.age = ageself.height = heightuser = User(name="baoshan", age=31, height=170) print(user.name, user.age, user.height)namedtuple實現(xiàn)
方式1:
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書! ''' from collections import namedtupleUser = namedtuple("User", ["name", "age", "height"]) user = User(name="baoshan", age=31, height=170) print(user.name, user.age, user.height)方式2:
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書! ''' from collections import namedtupleUser = namedtuple("User", ["name", "age", "height"]) user_tuple = ("baoshan", 31, 170) user = User(*user_tuple) print(user.name, user.age, user.height)namedtuple的優(yōu)勢
# namedtuple直接可以創(chuàng)建一個類 # 優(yōu)勢1: 代碼簡潔 # 優(yōu)勢2: 內(nèi)存小,效率高 數(shù)據(jù)處理方面很有優(yōu)勢 user_info_dict = user._asdict() print(user_info_dict)# namedtuple可以轉(zhuǎn)換為dict name, age, *others = user print(name, age, *others)# namedtuple可以拆包總結(jié)
以上是生活随笔為你收集整理的Python的collections之namedtuple的使用及其优势的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python Selenium 常用方法
- 下一篇: catboost原理以及Python代码