How to use python named tuples

王林
Release: 2023-05-02 23:13:05
forward
1529 people have browsed it

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)
Copy after login

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)
Copy after login

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)
Copy after login

Convert a dictionary to a named tuple:

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

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()
Copy after login

Convert a named tuple to a tuple:

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

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': , 'g': , 'b': < class 'float'>, 'alpha': };

  • 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)
Copy after login

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)
Copy after login

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)
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!