Home >Backend Development >Python Tutorial >python collection module

python collection module

不言
不言Original
2018-04-09 12:03:151846browse

The content shared with you in this article is about the collection module of python, which has certain reference value. Friends in need can refer to it

Collection module of python

collections The module provides several additional data types based on the built-in data types, such as int, str, list, dict, etc.

1.namedtuple(): Generate a tuple subclass that can use names to access element content
2.deque: Double-ended queue, which can quickly append and add from the other side Export object
3.Counter: Counter, mainly used for counting
4.OrderedDict: Ordered dictionary
5.defaultdict: Dictionary with default values

One: namedtuple(), named tuples.

tuple is an immutable collection. namedtuple is a function. It is used to construct a custom tuple object and specifies the number of tuple elements. Certain elements of the tuple can be referenced through attributes rather than indexes. elements. We can easily customize a data type through namedtuple, which has the immutable attributes of tuple and can be referenced based on the attributes.

from collections import namedtuple
piont=namedtuple('piont',['x','y'])
p=piont(2,1)
print(p)
print("x =",p.x)
print("Y =",p.y)

>>>isinstance(p,piont)
True
>>>isinstance(p,tuple)
True

类似的创建一个圆,通过坐标,半径r。用namedtuple构建
Cirle=namedtup(‘Circle’,['x','y','r'])


2、有序字典(orderedDict )
dict中key是无序的,在做迭代时,无法确认key的顺序。
orderdDict是对字典类型的补充,他记住了字典元素添加的顺序
from collections import OrderedDict
od=OrderedDict([('a',1),('z',2),('c',3)])// 有序字典顺序是插入进去的顺序排列的
print(od)
d=dict([('a',1),('z',2),('c',3)])  //字典是无序的,key的顺序是变化的
print(d)
3、默认字典(defaultdict)
defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。
我们都知道,在使用Python原生的数据结构dict的时候,如果用 d[key] 这样的方式访问, 当指定的key不存在时,是会抛出KeyError异常的。但是,如果使用defaultdict,只要你传入一个默认的工厂方法,那么请求一个不存在的key时, 便会调用这个工厂方法使用其结果来作为这个key的默认值。
4、计数器Counter
Counter是对字典类型的补充,用于追踪值的出现次数。
具备字典的所有功能+自己的功能
from collections import Counter
c=Counter(['11','22','11','33','11','44','55'])
c2=Counter("abcdefdasfdsafaf")
print(c)
print(c2)
most_common(self, n=None),数量从大到小排列,获取前N个元素。
elements(self) 计数器中的所有元素。注:此处非所有元素集合,而是包含所有元素集合的迭代器sorted(c.elements())
update(self,iterable=None,**keds):更新计数器,其实是增加计数器,如果没有则新建。
c.update('witch')
subtract(self, iterable=None, **kwds):相减,原来的计数器中的每一个元素的数量减去后添加的元素的数量c.subtract('witch')

Related recommendations:

Basic content of Python: collections module

In-depth understanding of Python collection module and deep and shallow copy

The above is the detailed content of python collection module. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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