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!

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

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

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

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

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

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

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


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

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
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools

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.
