collections.namedtuple用來建構帶有字段名的元組。對應類型為typing.NamedTuple(可用作超類別)。
namedtuple物件的定義:
collections.namedtuple(typename, field_names, verbose=False, rename=False, defaults=None, module=None) :
typename:元組名稱
field_names:是欄位序列(如,[‘x’, ‘y’]) ;
rename:當true時,當欄位名稱無效時(如,重新名稱或使用關鍵字)會被自動替換為位置名稱(如,_1);
defaults:字段的預設值,若為iterable對象,則依序對應field_names中字段的缺省值;
from collections import namedtuple Color = namedtuple("Color", "r g b alpha") def convert_to_color(desc: str, alpha: float = 0.0): if desc == "green": return Color(r=50, g=205, b=50, alpha=alpha) elif desc == "blue": return Color(r=50, g=0, b=255, alpha=alpha) else: return Color(r=50, g=0, b=0, alpha=alpha)
從可迭代對象(Iterable )建構具名元組:
c = Color._make([10, 20, 30, 0.1]) nc = Color._make((10, 20, 30, 0.1)) print("r:", c.r)
具名元組修改:不能直接修改裡面的值,可透過_replace建構一個新的:
c = {"r": 50, "g": 205, "b": 50, "alpha": 0.5} nc = c._replace(r=100)
#把字典轉換為具名元組:
c = {"r": 50, "g": 205, "b": 50, "alpha": 0.5} nc = Color(**c)
具名元組轉換為字典(透過_asdict方法):
c = Color(r=50, g=0, b=0, alpha=0.5) d = c._asdict()
具名元組轉換為元組:
c = Color(r=50, g=0, b=0, alpha=0.5) t = tuple(c)
屬性_fields包含所有欄位的元組:如('r', 'g', 'b', 'alpha');
屬性__annotations__包含欄位與對應類型的字典:如{'r':
屬性_field_defaults保證有初始值的欄位與初始值的字典:如{ 'alpha': 0.0};
具名元組排序:透過operator庫中的attrgetter可指定排序欄位:
from operator import attrgetter colors = [ Color(r=50, g=205, b=50, alpha=0.1), Color(r=50, g=205, b=50, alpha=0.5), Color(r=50, g=0, b=0, alpha=0.3) ] out = sorted(colors, key=attrgetter("alpha")) print(out)
字典dict是一種非常通用的資料結構,很容易被濫用,同時相對namedtuple,有以下問題:
from dataclasses import dataclass # frozen设为true后,字段内容将不允许修改(与namedtuple完全类似) # 否则可修改字段;并可任意添加字段(如,c.n=1); @dataclass(frozen=True) class DColor: """A regular class that represents a color.""" r: float g: float b: float alpha: float = 0.0 # c = DColor(r=10, g=20, b=30) c = DColor(10, 20, 30)
from typing import NamedTuple class NColor(NamedTuple): """A namedtuple that represents a color.""" r: float g: float b: float alpha: float = 0.0 nc = NColor(100, 110, 120)
以上是python具名元組如何使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!