directory

  • 0. Study materials

  • 1. collections

    • 1.1 the tuple
  • 1.2 nametuple

  • 1.3 defaultdict

  • 1.4 a deque

  • 1.5 the Counter

  • 1.6 OrderDict

  • 1.7 ChainMap

0. Study materials

www.imooc.com/video/16361

1. collections

Owned data structures:

__all__ = ['deque'.'defaultdict'.'namedtuple'.'UserDict'.'UserList'.'UserString'.'Counter'.'OrderedDict'.'ChainMap']
Copy the code

1.1 the tuple

  • Immutable (performance optimized, thread-safe, dict keys (requiring objects to be hashed), unpacked), iterable

  • Unpacking: Automatically maps the location values to variables

    # Unpack: Automatically map positional values to variables
    one, two, three = tuple_demo
    print(one, two, three)  # 1 3 5
    
    # unpack: the case where only the first value is needed
    on, *other = tuple_demo
    print(on)   # 1
    Copy the code

1.2 nametuple

#! /usr/bin/env/python3
# -*- coding:utf-8 -*-
"""
@project: collections_mkw
@author: zy7y
@file: nametuple_test.py
@ide: PyCharm
@time: 2020/8/28
"""
from collections import namedtuple

The first argument is a type name, and the second argument list is an attribute list of the generated class
User = namedtuple("user"["name"."age"."height"])

user = User(name="zy7y", age=18, height=157)
print(user.name, user.age, user.height)

# Variable parameters, meta - progenitor package, one of the function parameters
user_tuple = ("zy7y".18)
User_tuple unpack zy7y 18 in sequence
user_zy7y = User(*user_tuple, 157)
print(user_zy7y.name, user_zy7y.age, user_zy7y.height)      # zy7y 18 157

# dictionary unpacking, one of the methods of function parameter passing
user_dict = {
    "name": "kelan"."age": 17."height": 158
}
user_dict_zy7y = User(**user_dict)
print(user_dict_zy7y.name, user_dict_zy7y.age, user_dict_zy7y.height)  # kelan 17 158

The # _make method takes an iterable
user = User._make('str')
print(user.name, user.height, user.age)    # s r t

# _asdict() converts the class attribute (nametuple) to Orderdict
user_dict = user._asdict()
print(user_dict)  # OrderedDict([('name', 's'), ('age', 't'), ('height', 'r')])

# nametuple unpacking
name, age, height = user
print(name, age, height)    # s t r
Copy the code

1.3 defaultdict

www.imooc.com/video/16364

Defaultdict implements dictionary nesting
def gen_defult() :
    return {
        "name": "zy7y"
    }

defaultdict = defaultdict(gen_defult)
print(defaultdict["name"])

count_user = ["a"."b"."c"."a"."b"]
# Count the number of occurrences of each of the above values

count_user_dict = {}
for user in count_user:
    if user not in count_user_dict:
        count_user_dict[user] = 1
    else:
        count_user_dict[user] += 1
print(count_user_dict)  # {'a': 2, 'b': 2, 'c': 1}

from collections import defaultdict
Use defaultdict. Pass the callable int\list\ function
dt = defaultdict(int)
for user in count_user:
    dt[user] += 1
print(dt)   # defaultdict(<class 'int'>, {'a': 2, 'b': 2, 'c': 1})
Copy the code

1.4 a deque

# deque: double-ended queue
from collections import deque
# deque(iterable)
user_list = deque(["zy"."7y"])
Add the queue tail
user_list.append("kn")
Add to queue
user_list.appendleft("tn")
print(user_list)

# extend: Merging two deques does not return a new deque
# insert(subscript, value): Specify the subscript position, insert a data
Copy the code

1.5 the Counter

# Counter statistics, pass in the iterable
user_list = Counter(user_list)  # Counter({'tn': 1, 'zy': 1, '7y': 1, 'kn': 1})
# Post-merge statistics
user_list.update(["zy"."7y"])  # Counter({'tn': 1, 'zy': 1, '7y': 1, 'kn': 1})
print(user_list)

# Count the top n most content
result = user_list.most_common(3)    # [('zy', 2), ('7y', 2), ('tn', 1)]
print(result)
Copy the code

1.6 OrderDict

# OrderedDict: python3 dict orderdDict is always ordered
from collections import OrderedDict

user_dict = OrderedDict()
user_dict["key"] = 1
user_dict["kv"] = 2
# remove the last one without passing in a key
print(user_dict.popitem())
print(user_dict)    # {'key': 1}
user_dict["kv"] = 2
# Move the element to a location
user_dict.move_to_end("kv".False)
""" '''Move an existing element to the end (or beginning if last is false). Raise KeyError if the element does not Exist. '' moves an existing element to the end (or to the beginning if last is false). If the element does not exist, a KeyError is raised. "" "
print(user_dict)
Copy the code

1.7 ChainMap

# ChainMap
from collections import ChainMap
user_dict1 = {"a": 1."b": 2}
user_dict2 = {"c": 3."d": {"k": "v"}}
new_dict = ChainMap(user_dict1, user_dict2)
print(new_dict.maps, type(new_dict.maps))  # Convert to a list
# dynamically add new_dict.maps to return a new ChainMap
new_map = new_dict.new_child({"ss": 11})
for k, v in new_dict.items():
    print(k, v)
Copy the code