Python中元組的函式

2021-09-25 11:18:11 字數 944 閱讀 3484

定義乙個帶欄位名的元組

from collections import namedtuple

user = namedtuple('user',['name','***','age'])

user = user('lisi','male',12)

print(user) //user(name='lisi',***='male',age=12)

_fields:元組的屬性

print(user._fields)

//執行結果:('name','***','age')

_make():可以通過迭代物件來建立乙個元組(user物件)

user = user._make(['wangmazi','male',18])

print(user) //user(name='wangmaizi',***='male',age=18)

print(user.name) //wangmaizi

_replace():元素替換

user = user._replace(age=20)

print(user) //user(name='wangmaizi',***='male',age=20)

_asdict():將user物件轉換為字典,返回值為collections.ordereddice

print(user._asdict())

//執行結果:ordereddict([('name', 'wangmazi'), ('***', 'male'), ('age', 20)])

python中元組的簡介

t 1,2.3,true,star print t print type t 執行結果為 1,2.3,true,star t1 1,2,3 4 print t1 執行結果為 1,2,3,4 4 t2 hello print type t2 執行結果為 allowusers root westos r...

python中元組的使用

我的學習筆記 markdown真的是乙個很好用的電子筆記,以前總習慣手寫筆記,費時費力,也不好展現。接觸到csdn這個格式後,又了解了一下markdown這個排版美觀的輸出形式,真的是大愛。我自用的是typora,據了解還有其他的。重點是可以直接上傳我的學習筆記到csdn超級方便。因為想學習演算法類...

Python中元組的使用

2 命名元組 注意 元組只有乙個元素時一定要加逗號,例如b 1 b的型別為int a 空元組b 1 c 1,d 1,mm 2,3 print a,type a print b,type b 1 print c,type c 1,print d,type d 1,mm 2,3 a 2 7 b 1,2 ...