Python的collections之namedtuple的使用及其优势
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Python的collections之namedtuple的使用及其优势
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                類實現:
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實現
方式1:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和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:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和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的優勢
# namedtuple直接可以創建一個類 # 優勢1: 代碼簡潔 # 優勢2: 內存小,效率高 數據處理方面很有優勢 user_info_dict = user._asdict() print(user_info_dict)# namedtuple可以轉換為dict name, age, *others = user print(name, age, *others)# namedtuple可以拆包總結
以上是生活随笔為你收集整理的Python的collections之namedtuple的使用及其优势的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Python Selenium 常用方法
- 下一篇: catboost原理以及Python代码
