You can’t use Python without data structures, namely, list-list, tuples-tuple, and Dictionaries.

So in practice we’re going to have to manipulate more of the data in these structures. For example, to add an element after a list, the append() method is used.

In addition to these operations themselves, there is also a Python built-in module called Collections that provides quite a few methods to use, which I’ll take a look at today.

A Counter,

This is a counter that can be used to easily count the number of occurrences of elements such as strings, lists, Tuples, etc.

String

From collections import Counter c = Counter("HelloKitty") print(c) # 1, 'K': 1, 'i': 1, 'y': 1})Copy the code

List

From collections import Counter c = Counter([" apple ", "cherry ", 1, 1, 4, 4, 5]) print(c) # 1, 'cherry ': 1, 5: 1})Copy the code

Second, the deque

We like to use lists to store data, because it is very convenient. The downside of a list is that it’s fast if you access elements by index, but slow to insert and delete elements. Of course, you won’t notice it when the data is small, but you’ll only notice it when the data is large, because the list is a linear data structure. For example, if you insert a list, you’ll need to move all the elements after it by one place. In addition to implementing list append() and pop(), deque provides appendLeft () and popleft() so that we can easily add and remove operations to and from the other end of the list.

from collections import deque deque_list = deque(['a', 'b', 'c', 'd']) deque_list. Append (" apple ") deque_list. Appendleft (' eat ') print (deque_list) # run results: deque ([' eat ', 'a', 'b', 'c', 'd', 'apple'])Copy the code

Third, OrderedDict

Using Python, you naturally know that keys in Dict dictionaries are unordered. If you want to keep keys in order, use OrderedDict.

From collections import OrderedDict list_a = [(1, "apple "), (2," banana "), (3, "watermelon "), (4, "Mango ")] order_dict = OrderedDict(list_a) print(order_dict) # D: \ Daily lambda python whatiscollections. Py OrderedDict ([(1, "apple"), (2, "banana"), (3, 'watermelon'), (4, 'mango)])Copy the code

If you need to use them in a scenario, you can try them out.