search
HomeBackend DevelopmentPython TutorialPython basic content: collections module

collections is a built-in collection module in Python that provides many useful collection classes. 1.Counter Counter is a simple counter, for example, counting the number of characters appearing: >>> import
collections>>> obj =
collections.Counter('applebanana')> ;>> print(obj)Counter({'a': 4, 'n':
2, 'p': 2, 'e': 1, 'l': 1, 'b': 1 }) 2.OrderedDict ordered dictionary When using dict, the Key is unordered. When iterating over dict, we cannot determine the order of Keys. If you want to maintain the order of Keys, you can use OrderedDict:>>> od =
collections.OrderedDict()>>> od['k2']
='k2'>> > od['k1'] =
'k1'>>> odOrderedDict([('k2',
'k2'), ('k1', 'k1')]) or> ;>> od =
collections.OrderedDict([('k2','v2'),('k1','v1')])>>> odOrderedDict([('k2',
'v2'), ('k1', 'v1')]) 3.defaultdict The default dictionary will set a default type for the dictionary value import collectionsnum =
[11,22,33,44, 55,66,77,88,99] #Add the default list type my_dic for the value of the my_dic dictionary =
collections.defaultdict(list) for i in num: if i > 66: my_dic['k1'].append (i) else: my_dic['k2'].append(i)print(my_dic) 4.namedtuple Named Tuple Namedtuple is a function that is used to create 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 easily define a data type using namedtuple, which has the invariance of tuple and can be referenced based on attributes. It is very convenient to use>>>person = collections.namedtuple('pp', ['name','age'])>>>p = person('apple',2)>>>print(p.name)>>>print(p.age) 5.deque two-way queue When using a list to store data, accessing elements by index is very fast, but inserting and deleting elements is very slow, because the list is linear storage, and when the amount of data is large, the efficiency of insertion and deletion is very low. Deque is a two-way list for efficient implementation of insertion and deletion operations, suitable for queues and stacks:>>> dli =
collections.deque([1,2,3])>>>
dli.append(4)>>> dlideque([1, 2, 3, 4])>>>
dli.appendleft(5) #appendleft insert data to the left>> ;> dlideque([5, 1, 2, 3, 4]) 6.queue single-item queue (in the queue module) import queueq = queue.Queue()q.put(123)q.put(456)print(q .qsize())print(q.get())#q.get() will take out the data in the single item queue in sequence print(q.get())

The above is the detailed content of Python basic content: collections 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
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.