python 库整理: collections.namedtuple
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                python 库整理: collections.namedtuple
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.                        
                                ??????namedtuple創(chuàng)建一個(gè)和tuple類似的對(duì)象,而且對(duì)象擁有可訪問的屬性。
1 nametuple的創(chuàng)建?
User1 = namedtuple('User_name', ['name', 'sex', 'age']) user = User1(name='lwj', sex='male', age=21) user ''' User_name(name='lwj', sex='male', age=21) ''' User2 = namedtuple('User_name2', ['name', 'sex', 'age'])user2 = User2._make(['kongxx', 'male', 21]) user2 #User_name2(name='kongxx', sex='male', age=21)2 讀取nametuple條目
和類一樣
print(user.name) print(user.sex) print(user.age) ''' lwj male 21 '''3 替換條目?jī)?nèi)容
user = user._replace(age=22) print(user) #User_name(name='lwj', sex='male', age=22)4 轉(zhuǎn)換成字典
print(user._asdict()) #OrderedDict([('name', 'lwj'), ('sex', 'male'), ('age', 22)])總結(jié)
以上是生活随笔為你收集整理的python 库整理: collections.namedtuple的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 报错解决方案:ERROR: Cython
- 下一篇: 错误解决 :Microsoft Visu
