Python module collections

1. In-depth understanding of the function of tuple in python

Basic Features

# iterable
name_tuple = ('0bug', '1bug', '2bug')
for name in name_tuple:
    print(name)
    
# immutable
name_tuple = ('0bug', '1bug', '2bug')
name_tuple[0] = 'bug'  # TypeError: 'tuple' object does not support item assignment

# Immutable is not absolute
change_tuple = (1, 2, [3, 4])
change_tuple[2][1] = 5
print(change_tuple)  # (1, 2, [3, 5])

# unpack
lcg_tuple = ('0bug', '25', '175')
name, age, height = lcg_tuple
print(name, age, height)

lcg_tuple = ('0bug', '25', '175')
name, *other = lcg_tuple
print(other)  # ['25', '175']

Where is tuple better than list?

1. Performance optimization

2. Thread Safety

3. Can be used as the key of dict

# The tuple object is hashable and can be used as a dictionary key
my_tuple = ('0bug','1bug')
dec = {}
dic[my_tuple] = 'name'
print(dic)  # {('0bug', '1bug'): 'name'}

4. Unpacking features

If you take the C language as an analogy, Tuple corresponds to struct, and List corresponds to array

 

2. Detailed explanation of the function of namedtuple

 

 

3. Detailed explanation of the function of defaultdict

4. Detailed explanation of the function of deque

5. Detailed explanation of Counter function

6. Detailed explanation of OrderedDict function

7. Detailed explanation of ChainMap function

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324941983&siteId=291194637