Better named tuple than tuple in Python

Posted by sandthipe on Wed, 13 Nov 2019 20:34:40 +0100

First, thinking

1. What is tuple?

  • Immutable sequence type
  • List that cannot be modified

2. What operations does tuple support?

  • Tuple is a sequence type, supporting all operations of sequence type
  • Value by index
one_tuple = ("Excellent", 17, "male", "coding", "Never Stop Learning!")
one_tuple[-1]
  • Slicing operation
one_tuple = ("Excellent", 17, "male", "coding", "Never Stop Learning!")
one_tuple[3:5]
  • Member action (in or not in)
one_tuple = ("Excellent", 17, "male", "coding", "Never Stop Learning!")
"Excellent" in one_tuple
  • Connection operation (+)
one_tuple = ("Excellent", 17, "male", "coding", "Never Stop Learning!")
two_tuple = ("That is really right!", )
one_tuple + two_tuple
  • Repeat operator (*)
one_tuple = ("Excellent", 17, "male", "coding", "Never Stop Learning!")
one_tuple * 2
  • Traversal (for)
one_tuple = ("Excellent", 17, "male", "coding", "Never Stop Learning!")
for value in one_tuple:
    print(value)
  • Length (len)
one_tuple = ("Excellent", 17, "male", "coding", "Never Stop Learning!")
len(one_tuple)
  • Other built-in functions (all, any, max, min, list, tuple, enumerate, sorted, etc.)

3. What are the disadvantages of tuples (pain points)?

  • The biggest pain point is that it can only be obtained by numerical index
  • When the elements in a tuple are very large, it is not convenient to take values through the index, and the memory consumption is also large

3. Named tuple

1. definition

To use a named tuple:

# Encapsulating a tuple as a class, you can access the value in the tuple through the field name (property name)
# Supports all tuple operations
from collections import namedtuple

# 1. Define a class
Love = namedtuple("Love", "name gender age love_into hobby motto")

# 2. Create object
keyou = Love("Excellent", "Handsome man", 17, "Lemon little girl", "Coding", "Never Stop Learning!")

# 3. Get the value of the named tuple
print(keyou[1])     # Support index value of tuple
print(keyou[-2:])   # Supporting slice
print(keyou.name)   # Value can be obtained by field name

There are three ways to define a named tuple class, as well as the rename and defaults parameters:

from collections import namedtuple


# 1. Define a class
# Method 1, passing a string with a space between property names
Love = namedtuple("Love", "name gender age love_into hobby motto")

# Method 2, you can also separate each attribute name with a comma
Love = namedtuple("Love", "name,gender,age,love_into,hobby,motto")

# Method 3, passing a sequence type (list, tuple) consisting of attribute names
fields = ["name", "gender", "age", "love_into", "hobby", "motto"]
Love = namedtuple("Love", fields)

# Explain:
# Property name should conform to the naming standard of identifier
# It can only be composed of numbers, letters and underscores
# Cannot start with a number
# Cannot have the same name as a keyword, system function, or class
# If the property name does not conform to these specifications, will an error be reported Report wrong
fields = ["1name", "class", "def", "love_into", "hobby", "motto"]
Love = namedtuple("Love", fields)

# What if you pass a property name that doesn't conform to the specification and don't want it to report an error It can be done
# If the rename parameter is set to True, when the property name does not conform to the specification, it will automatically help us change the property name that does not conform to the specification to underscore plus numeric index value
fields = ["1name", "class", "def", "love_into", "hobby", "motto"]
Love = namedtuple("Love", fields, rename=True)

# What if some properties have default values How to set it up?
# You can set the defaults parameter as a sequence type
# Default attributes from right to left
fields = ["1name", "class", "def", "love_into", "hobby", "motto"]
Love = namedtuple("Love", fields, rename=True, defaults=["Coding", "Never Stop Learning!"])


# 2. Create object
# keyou = Love("Keyou", "Shuai man", 17, "Lemon little girl", "Coding", "Never Stop Learning!")
# Since the hobby and button attributes already have default values, all of them can be passed without passing
keyou = Love("Excellent", "Handsome man", 17, "Lemon little girl")


# 3. Get the value of the named tuple
print(keyou[1])     # Support index value of tuple
print(keyou[-2:])   # Supporting slice
# print(keyou.1name)   # Value can be obtained by field name
print(keyou._0)   # Value can be obtained by field name

2. create

There are two ways to create objects:

# How to create objects
from collections import namedtuple


# 1. Define a class
Love = namedtuple("Love", "name gender age love_into hobby motto")

# 2. Create object
# Method 1, call the constructor to create the object
keyou = Love("Excellent", "Handsome man", 17, "Lemon little girl", "Coding", "Never Stop Learning!")

# Method 2: use the "make" method to create the object
one_person_value = ["Excellent", "Handsome man", 17, "Lemon little girl", "Coding", "Never Stop Learning!"]  # Any sequence type will do
keyou = Love._make(one_person_value)


# 3. Get the value of the named tuple
print(keyou[1])     # Support index value of tuple
print(keyou[-2:])   # Supporting slice
print(keyou.name)   # Value can be obtained by field name

3. value

There are three ways to get the elements in a named tuple:

# How to get the elements in a named tuple
from collections import namedtuple


# 1. Define a class
Love = namedtuple("Love", "name gender age love_into hobby motto")

# 2. Create object
one_person_value = ["Excellent", "Handsome man", 17, "Lemon little girl", "Coding", "Never Stop Learning!"]  # Any sequence type will do
keyou = Love._make(one_person_value)


# 3. Get the value of the named tuple
# Method 1: take values through index or slice
print(keyou[1])     # Support index value of tuple
print(keyou[-2:])   # Supporting slice

# Method 2: take value by field name
print(keyou.name)

# Method 3, get the value through getattr
print(getattr(keyou, 'gender'))

4. Other operations

Other operations supported by named tuples:

  • _asdict method
  • _replace method
  • _fields property
  • _Field? Defaults property
# Other operations supported by named tuples

from collections import namedtuple


# 1. Define a class
fields = ["name", "age", "gender", "love_into", "hobby", "motto"]
Love = namedtuple("Love", fields, rename=True, defaults=["Coding", "Never Stop Learning!"])

# 2. Create object
one_person_value = ["Excellent", "Handsome man", 17, "Lemon little girl", "Coding", "Never Stop Learning!"]  # Any sequence type will do
keyou = Love._make(one_person_value)


# 3. Get the value of the named tuple
# Method 1: take values through index or slice
# print(keyou[1])     # Support index value of tuple
# print(keyou[-2:])   # Supporting slice

# Method 2: take value by field name
# print(keyou.name)

# Method 3, get the value through getattr
# print(getattr(keyou, 'gender'))


# 4. Other operations
# _Adict method, which converts tuples into Dictionaries
one_dict = keyou._asdict()
print(dict(one_dict))

# _replace method, modify the value in the tuple, and a new tuple group will be created. The previous tuple has not been modified
print("keyou The brand number of is:{}".format(id(keyou)))
new_keyou = keyou._replace(age=16)
print("new_keyou The value is:{}\n The new door brand is:{}\n".format(new_keyou, id(new_keyou)))

# _fields, get all attribute names of the named tuple
print(keyou._fields)

# _Field? Defaults, get all the attribute defaults of the named tuple
print(keyou._fields_defaults)

5. Application scenarios

  • When the test data is read from Excel (csv, json, database), when it is processed in Python, the namedtuple is often used to carry the data
  • All scenarios where tuples are needed to process data can

Topics: Python Attribute Excel JSON Database