Home >Backend Development >Python Tutorial >How to use python named tuples

How to use python named tuples

王林
王林forward
2023-05-02 23:13:051553browse

collections.namedtuple is used to construct tuples with field names. The corresponding type is typing.NamedTuple (can be used as a superclass).

Named tuple

Definition of namedtuple object:

collections.namedtuple(typename, field_names, verbose=False, rename=False, defaults=None, module=None) :

  • typename: tuple name

  • field_names: is a field sequence (e.g., [‘x’, ‘y’]) ;

  • rename: When true, the field name if it is invalid (for example, has the same name or uses keywords) will be automatically replaced with the position name (for example, _1);

  • defaults: The default value of the field. If it is an iterable object, it corresponds to the default value of the field in field_names in turn;

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)

From the iterable object (Iterable ) Construct a named tuple:

c = Color._make([10, 20, 30, 0.1])
nc = Color._make((10, 20, 30, 0.1))

print("r:", c.r)

Tuple operation

Modification of named tuple: The value inside cannot be modified directly, and a new one can be constructed through _replace:

c = {"r": 50, "g": 205, "b": 50, "alpha": 0.5}
nc = c._replace(r=100)

Convert a dictionary to a named tuple:

c = {"r": 50, "g": 205, "b": 50, "alpha": 0.5}
nc = Color(**c)

Convert a named tuple to a dictionary (via the _asdict method):

c = Color(r=50, g=0, b=0, alpha=0.5)
d = c._asdict()

Convert a named tuple to a tuple:

c = Color(r=50, g=0, b=0, alpha=0.5)
t = tuple(c)

Attribute

  • Attribute_fields contains a tuple of all fields: such as ('r', 'g', 'b', 'alpha');

  • Attribute __annotations__ contains a dictionary of fields and corresponding types: such as {'r': e13446bebb88208a1ed1b67eb6c71d15, 'g': e13446bebb88208a1ed1b67eb6c71d15, 'b': 15fe1a1f411018ce39706d720ae2d2a8, 'alpha': e13446bebb88208a1ed1b67eb6c71d15};

  • Attribute_field_defaults guarantees a field with an initial value and a dictionary of initial values: such as { 'alpha': 0.0};

Sort

Named tuple sorting: The sorting field can be specified through the attrgetter in the operator library:

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)

with Dictionary comparison

Dictionary dict is a very general data structure that is easily abused. At the same time, compared with namedtuple, it has the following problems:

  • Dictionaries are not hashable. So it cannot be stored in a set or other dictionary;

  • Dictionaries are mutable and any number of new keys can be added as needed;

#Similar to dict, in namedtuple values ​​can be assigned to individual variables and used as needed. However:

namedtuple is immutable and new values ​​(keys) will not be accidentally added;

Data Class

For details of data classes, please refer to "Data Class (dataclass)" Introduction".

dataclass modification

The data class (Data Class) was introduced in python3.7, which can be regarded as a "variable namedtuple with a default value":

  • Can easily add doc;

  • can define optional fields;

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)

Inherit NamedTuple

By inheritance NamedTuple can also be easily defined (at the same time, the initial value of the field can be defined, and the field with an initial value must follow the non-initial field):

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)

The above is the detailed content of How to use python named tuples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete