1. Module description
collections is a built-in module of Python. The so-called built-in module refers to the module that is packaged inside Python and can be used directly without installation. .
- collections contains some special containers, providing an alternative to Python's built-in containers, such as: list, dict, set, tuple.
- namedtuple: A tuple containing a name can be created.
- deque: A container similar to a list, which can quickly add and delete elements at the head and tail of the queue.
- OrderedDict: A subclass of dict that can remember the order in which elements are added.
- defaultdict: A subclass of dict that can call functions that provide default values.
- Counter: A subclass of dict that calculates hashable objects.
2. Actual code
(1) testNamedTuple function
Python provides many very easy-to-use basic types, such as the immutable type tuple, which we can easily Use it to represent a binary vector.
namedtuple is a function that creates a custom tuple object and specifies the number of tuple elements, and can use attributes instead of indexes to reference an element of the tuple.
In this way, we can use namedtuple to easily define a data type, which has the invariance of tuple and can be referenced based on attributes, making it very convenient to use.
In this example, we use a three-dimensional coordinate x, y, z to define a tuple object. There are three object elements, and then the corresponding value can be referenced through the coordinate value.
from collections import namedtuple from collections import deque from collections import defaultdict from collections import OrderedDict from collections import Counter def testNamedTuple(): vector=namedtuple('vector',['x','y','z']) flag=vector(3,4,5) print(type(flag)) print(isinstance(flag,vector)) print(isinstance(flag,tuple)) #通过这里的判定我们就可以知晓它是元组类型 print(flag.x,flag.y,flag.z)
(2) testDeque function
deque is a generalized implementation of stack and queue, and deque is the abbreviation of "double-end queue".
Deque supports thread-safe, memory-efficient insertion and deletion of elements at both ends of deque with approximately O(1) performance. Although list also supports similar operations, it is mainly optimized for fixed-length operations. , resulting in a time complexity of O(n) on pop(0) and insert(0,v) (which will change the position and size of the data).
In data structures, we know that queues and stacks are two very important data types, one is first in, first out, and the other is last in, first out.
In python, 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, the efficiency of insertion and deletion is very low. .
Deque is a doubly linked list structure for efficient implementation of insertion and deletion operations. It is very suitable for implementing data structures such as queues and stacks.
def testDeque(): list1=[x*x for x in range(101)] delist=deque(list1) #对列表进行了一次再处理,让list1列表变成了双向链表结构 delist.append(1000)#将x添加到deque的右侧 delist.appendleft(2000)#将x添加到deque的左侧 delist.pop(1000)#移除和返回deque中最右侧的元素,如果没有元素,将会报出IndexError; delist.popleft()#移除和返回deque中最左侧的元素,如果没有元素,将会报出IndexError; delist.count(1)#返回deque中元素等于1的个数 delist.remove(10000)#移除第一次出现的value,如果没有找到,报出ValueError; delist.reverse()#反转deque中的元素,并返回None; list2=[1,3,4,5] delist.extend(list2)#将可迭代变量iterable中的元素添加至deque的右侧 delist.extendleft(list2)#将变量iterable中的元素添加至deque的左侧,往左侧添加序列的顺序与可迭代变量iterable中的元素相反 delist.maxlen()#只读的属性,deque的最大长度,如果无解,就返回None delist.rotate(1)#从右侧反转n步,如果n为负数,则从左侧反转 delist.clear()#将deque中的元素全部删除,最后长度为0;
(3)testDefaultdict function
defaultdict is a subclass of the built-in data type dict. Its basic functions are the same as dict, except that it overrides a method __missing__(key) and adds a Writable object variable default_factory.
When using the dict dictionary type, if the referenced key does not exist, KeyError will be thrown. If you want a default value to be returned when the Key does not exist, you can use defaultdict.
def testDefaultdict(): dict1= defaultdict(lambda: 'default') #Key不存在时,返回一个默认值,就可以用default,defaultdict的其他行为跟dict是完全一样的 dict1["k1"]="v1" print(dict1["k2"]) list2= [('yellow',11),('blue',2),('yellow',3),('blue',4),('red',5),('red',10)] dict1 = defaultdict(list)#使用list作为default_factory,很容易将一个key-value的序列转换为一个关于list的词典 for k,v in list2: dict1[k].append(v) print(dict1)
(4) testOrderedDict function
OrderedDict is similar to a normal dictionary, except that it remembers the order in which elements are inserted. When iterating over an ordered dictionary, the returned elements are them The order of first addition. In this way dict is an ordered dictionary.
When using dict, keys are unordered. When iterating over a dict, we cannot determine the order of the keys. But if you want to keep the order of keys, you can use OrderedDict.
def testOrderedDict(): dict1=dict([('aaa', 111), ('ddd',444),('bbb', 222), ('ccc', 333)]) print(dict1) dict2 = OrderedDict([('ddd',444),('aaa', 111), ('bbb', 222), ('ccc', 333)])#OrderedDict的key会按照插入的顺序排列,不是key本身排序 print(dict2) dict3 = {"banana": 33, "apple": 222, "pear": 1, "orange": 4444} # dict sorted by key dict4=OrderedDict(sorted(dict3.items(), key=lambda t: t[0])) print("dict4",dict4) # dict sorted by value dict5=OrderedDict(sorted(dict3.items(), key=lambda t: t[1])) print("dict5",dict5) # dict sorted by length of key string dict6 = OrderedDict(sorted(dict3.items(), key=lambda t: len(t[0]))) print("dict6",dict6) print(dict6['apple'])
(5) testCounter function
def testCounter(): '''counter可以支持方便、快速的计数''' str1="abcdefgabcedergeghdjlkabcdefe" #将可迭代的字符串初始化counter str2=Counter(str1) print(str2) #从输出的内容来看,Counter实际上也是dict的一个子类 for k,v in str2.items(): print(k,v) dict3 = {"banana": 33, "apple": 222, "pear": 1, "orange": 4444,"apples":2}#将dict初始化counter dict4=Counter(dict3) print(dict4) print(dict4["test"])#Counter对象类似于字典,如果某个项缺失,会返回0,而不是报出KeyError; dict5=Counter(high=9,age=33,money=-1)#将args初始化counter print(dict5) #elements返回一个迭代器,每个元素重复的次数为它的数目,顺序是任意的顺序,如果一个元素的数目少于1,那么elements()就会忽略它; list1=list(dict5.elements()) print(list1) #most_common返回一个列表,包含counter中n个最大数目的元素 #,如果忽略n或者为None,most_common()将会返回counter中的所有元素,元素有着相同数目的将会以任意顺序排列; str1 = "abcdefgabcedergeghdjlkabcdefe" list1=Counter(str1).most_common(3) print(list1) if __name__ == '__main__': # testNamedTuple() # testCounter() testDefaultdict() # testDeque() # testOrderedDict()
The above is the detailed content of Let's talk about Collections, a built-in module of Python. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
