Home > Backend Development > Python Tutorial > A brief introduction to the collection module in python (with examples)

A brief introduction to the collection module in python (with examples)

不言
Release: 2018-09-25 16:52:51
Original
3126 people have browsed it

This article brings you a brief introduction to the collection module in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

collection module:

Based on the built-in data types (dict, list, set, tuple), the collections module also provides several additional data types: Counter, deque, defaultdict, namedtuple and OrderedDict etc.

1:namedtuple

Generate a tuple that can use the name to access the element content
For example: represents a coordinate

from collections import namedtuple
point = namedtuple('point',['x','y'])
p=point(1,2)
print(p.x)
print(p.y)
Copy after login
>>1
>>2
Copy after login

2:deque Double-ended queue:

Double-ended queue can quickly add and push objects from the other side.
When using list to store data, accessing elements by index is very fast, but inserting and deleting elements is very slow, because list is linear storage, and when the amount of data is large, insertion and deletion efficiency is very low

deque is a two-way list for efficient implementation of insertion and deletion operations, suitable for queues and stacks

from collections import deque
q=deque(['a','b','c'])
q.append('x')
q.appendleft('y')
print(q)
Copy after login
>>deque(['y', 'a', 'b', 'c', 'x'])
Copy after login

3: Counter counter

Counter, mainly used for counting
The purpose is for tracking The number of times a value comes out. It is an unordered container type, stored in the form of key-value pairs in a dictionary, where the element is used as the key, and its count is used as the value
The count value can be any interger (including 0 and negative numbers) ,

Create:

from collections import Counter
#创建一个空的类
c=Counter()
#从一个可迭代对象中创建
c=Counter('gallahad')
#从一个字典对象创建
c=Counter({'a':2,'b':4})
#从一组键值对创建
c=Counter(a=2,b=4)
Copy after login

Count value accesses with missing keys
When the accessed key does not exist, return 0 instead of KeyError; otherwise return its count

Count value access

c=Counter('gallahad')
print(c['a'])
print(c['z'])
>>3
>>0
Copy after login

Counter update (update and subtract)
You can use an iterable object or another Counter object to update the key-value pair

update increases

c=Counter('gallahad')
c.update('chengzheng')
print(c['e'])
>>2
d=Counter('holloword')
c.update(d)
print(c['l'])
>>4
Copy after login

subtract decreases

c=Counter('gallahad')
c.subtract('g')
print(c['g'])
>>0
d=Counter('all')
c.subtract(d)
print(c['l'])
>>0
Copy after login

Modification and deletion of keys
When the count value is 0, it does not mean that the element is deleted. To delete elements you should use del

c=Counter('gallahad')
print(c)
c['a']=0
print(c)
del c['l']
print(c)
>>Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
>>Counter({'l': 2, 'g': 1, 'h': 1, 'd': 1, 'a': 0})
>>Counter({'g': 1, 'h': 1, 'd': 1, 'a': 0})
Copy after login

elements():
Returns an iterator. The number of times an element is repeated is how many times the element is contained in the iterator. The elements are arranged in no definite order, and elements with a number less than 1 are not included.

c =Counter(a=4,b=2,c=0,d=-2)
a =list(c.elements())
print(a)
>>['a', 'a', 'a', 'a', 'b', 'b']
Copy after login

most_common():
Returns a top (n) list. If n is not specified, all elements are returned. When multiple elements have the same count value, the arrangement is unordered

c =Counter('xsgffikgkhgdyrduykkf')
a =c.most_common(3)
print(a)
Copy after login

Other operations:

sum(c.values())  # 所有计数的总数
c.clear()  # 重置Counter对象,注意不是删除
list(c)  # 将c中的键转为列表
set(c)  # 将c中的键转为set
dict(c)  # 将c中的键值对转为字典
c.items()  # 转为(elem, cnt)格式的列表
Counter(dict(list_of_pairs))  # 从(elem, cnt)格式的列表转换为Counter类对象
c.most_common()[:-n:-1]  # 取出计数最少的n个元素
c += Counter()  # 移除0和负值
Copy after login

4:OrderdDict is ordered Dictionary

Using a dictionary (dict), the keys are unordered. When iterating the dictionary, we cannot determine the order of the keys.
If you want the keys to be in order, you can use OrderdDict

from collections import OrderedDict

d=dict([('a',1),('b',2),('c',3)])
print(d)
od=OrderedDict([('a',1),('b',2),('c',3)])
print(od)
>>{'c': 3, 'b': 2, 'a': 1}
>>OrderedDict([('a', 1), ('b', 2), ('c', 3)])
Copy after login


Note: OrderdDict is sorted according to the order of insertion, not according to the key Sorted by itself.

od=OrderedDict([('a',1),('c',3),('b',2)])
print(od)
>>OrderedDict([('a', 1), ('c', 3), ('b', 2)])
Copy after login

5:defaultdict: dictionary with default values

Example:
has the following value set [11,22,33,44,55,66,77, 88,99,90...], save all values ​​greater than 66 to the first key of the dictionary, and save values ​​less than 66 to the value of the second key.

That is: {'k1': greater than 66, 'k2': less than 66}

from collections import defaultdict

values = [11, 22, 33,44,55,66,77,88,99,90]
my_dict = defaultdict(list)
for value in  values:
    if value>66:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)
print(my_dict)
Copy after login
>>defaultdict(<class &#39;list&#39;>, {&#39;k2&#39;: [11, 22, 33, 44, 55, 66], &#39;k1&#39;: [77, 88, 99, 90]})
Copy after login

The above is the detailed content of A brief introduction to the collection module in python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template