In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains how to use Python built-in module Collections. Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's take you to learn how to use Python built-in module Collections!
1. Module description
Collections is a built-in module of Python. The so-called built-in module refers to the module packaged inside Python and can be used directly without installation.
Collections contain special containers that provide an alternative to Python's built-in containers, such as lists, edicts, sets, and tuples.
namedtuple: You can create tuples that contain names.
deque: A list-like container that allows you to quickly add and delete elements at the head and tail of a queue.
OrderedDict: A subclass of dict that remembers the order in which elements are added.
defaultdict: A subclass of dict that calls functions that provide default values.
Counter: A subclass of dict that computes hashable objects.
2. Actual combat code (1) testNamedTuple function
Python provides a number of very useful basic types, such as the immutable tuple, which we can easily use to represent a binary vector.
namedtuple is a function that creates a custom tuple object, specifies the number of tuple elements, and refers to an element of the tuple as an attribute rather than an index.
In this way, we can easily define a data type with namedtuple, which has tuple immutability and can be referenced according to attributes, which is very convenient to use.
In this example, we use a three-dimensional coordinate x,y,z to define a tuple object. There are 3 object elements, and then the corresponding values can be referenced by coordinate values.
from collections import namedtuplefrom collections import dequefrom collections import defaultdictfrom collections import OrderedDictfrom collections import Counterdef testNamedTuple(): vector=namedtuple('vector',['x','y','z']) flag=vector(3,4,5) print(type(flag)) print(isinstance(flag,vector)) print(isinstance(flag,tuple)) #By judging here we can know that it is tuple type print(flag.x,flag.y,flag.z)(2) testDeque function
deque is a generalized implementation of stack and queue, deque is short for "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 supports similar operations, but it is optimized primarily for fixed-length operations, resulting in O(n) time complexity on pop(0) and insert(0,v)(which changes the location and size of the data).
In data structures, we know that queues and stacks are two very important data types, one first-in, first-out and one last-in, first-out.
In Python, when using list to store data, accessing elements by index is fast, but inserting and deleting elements is slow, because list is linear storage, and when the amount of data is large, insertion and deletion efficiency is very low.
Deque is a doubly linked list structure for efficient insertion and deletion operations, which 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) #Reprocesses the list once, making list1 a doubly linked list delist.append(1000)#Add x to the right of deque delist.appendleft(2000)#Add x to left of deque delist.pop(1000)#removes and returns the rightmost element in the deque, if there is no element, IndexError will be reported; delist.popleft()#removes and returns the leftmost element in the deque, if there is no element, IndexError will be reported; delist.count(1)#Returns the number of elements in deque equal to 1 delist.remove(10000)#Remove the first occurrence of value, if not found, report ValueError; delist.reverse()#Inverts elements in deque and returns None; list2=[1,3,4,5] delist.extend(list2)#Adds elements from iterable to the right of deque delist.extendleft(list2)#Add the elements of iterable to the left of deque, adding sequences to the left in the reverse order of the elements of iterable delist.maxlen()#read-only attribute, maximum length of deque, if no solution, returns None delist.rotate(1)#reverse n steps from right, if n is negative, reverse from left delist.clear()#Delete all elements in deque, the final length is 0;(3)testDefaultdict function
defaultdict is a subclass of the built-in data type dict. Its basic function is 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, KeyError is thrown if the referenced key does not exist. If you want to return a default value when Key does not exist, you can use defaultdict.
def testDefaultdict(): dict1= defaultdict(lambda: 'default')#If Key does not exist, return a default value, you can use default, defaultdict Other behaviors are exactly the same as dict dict1["k1"]="v1" print(dict1["k2"]) list2= [('yellow',11),('blue',2),('yellow',3),('blue',4),('red',5),('red',10)] dict1 = defaultdict(list)#Using list as default_factory, it is easy to convert a key-value sequence into a dictionary of lists 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, and when iterating over an ordered dictionary, returns elements in the order in which they were first added. A dictionary is an ordered dictionary.
When using dict, keys are unordered. When iterating through dict, we cannot determine the order of keys. But if you want to preserve 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 keys are sorted in the order of insertion, not the keys themselves 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 can support convenient and fast counting '' str1="abcdefgabcedergeghdjlkabcdefe" #Initialize counter for iterable string str2=Counter(str1) print(str2) #From the output, Counter is actually a subclass of dict for k,v in str2.items(): print(k,v) dict3 = {"banana": 33, "apple": 222, "pear": 1, "orange": 4444,"apples":2}#Initialize dict counter dict4=Counter(dict3) print(dict4) print(dict4["test"])#Counter object is similar to a dictionary, if an item is missing, it will return 0 instead of KeyError; dict5=Counter(high=9,age=33,money=-1)#Initialize args counter print(dict5) #elements returns an iterator, each element repeated as many times as it wants, in any order, and if the number of elements is less than 1, elements() ignores it; list1=list(dict5.elements()) print(list1) #most_common Returns a list of n elements with the maximum number of counter elements #, if n is ignored or None, most_common() will return all elements of counter, elements with the same number will be arranged in any order; str1 = "abcdefgabcedergeghdjlkabcdefe" list1=Counter(str1).most_common(3) print(list1)if __name__ == '__main__': # testNamedTuple() # testCounter() testDefaultdict() # testDeque() # testOrderedDict() At this point, I believe that everyone has a deeper understanding of "how to use Python built-in module Collections", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.