Joke Collection Website - Mood Talk - On Python's Named Tuples

On Python's Named Tuples

Python provides a tuple similar to a list, except that the elements of the tuple cannot be modified. Although it is sometimes convenient, it is not so intuitive because the data in tuples cannot be named.

Python introduced the factory function collections.namedtuple to construct tuples with field names.

(1) declaration and instantiation

We usually construct named tuples like this:

The following is an example of declaring a named tuple and its instantiation method:

Running results:

Here, a named tuple is created through collections.namedtuple to represent a playing card. Rank stands for the number of playing cards and suit stands for suit. You can instantiate a named tuple by field name or location. Select_card here means that a spade 10 has been drawn.

(2) Unique attributes and methods

Named tuples also have the following unique properties and methods.

Running results:

In addition, the corresponding attribute values in the named tuple can also be passed. Grammar:

Running results: