1. The decompression sequence is assigned to multiple variables
any sequence (or an iterative object ) can be extracted and assigned to multiple variables by a simple assignment statement. The only prerequisite is that the number of variables must be the same as the number of elements in the sequence .
' ACME ', 91.1, (+, +)]
>>> name, shares, price, date = Data>>> name, shares, Price, (year, Mon, day) = data>&G t;> name'ACME'>>> Year 2012
If the number of elements of an iterative object exceeds the number of variables, a valueerror is thrown. can be resolved with *, this only supports Python3. The iterative decompression syntax for the extension is designed specifically to extract an indeterminate number or an iterative object of any number of elements. The extracted is always the list, or empty if it is empty.
>>> *trailing, current = [Ten, 8, 7, 1, 9, 5, ten, 3]>>> trailing[10, 8, 7, 1, 9, 5, 10< c2>]>>> 3>>> First, *middle, last = grades>>> record = (' /c5>ACME', 123.45, (+), *_, (*_, year) = record>& gt;> name'ACME'>>> Year 2012
2. Queue
Collections.deque can generate a fixed size, or an unlimited size queue. You can perform actions to add and eject elements at both ends of the queue. The time complexity of inserting or deleting elements at both ends of the queue is O(1)
, and the time complexity of inserting or deleting elements at the beginning of the list is O(N)
.
>>> q = deque (maxlen=2)>>> Q.append (1)>>> Q.append (2)>>>Qdeque ([1, 2], maxlen=2)>>> Q.append (3)>>>Qdeque ([2, 3], maxlen=2)>>> q =deque ()>>> Q.append (1)>>> Q.append (2)>>>Qdeque ([1, 2])>>> Q.appendleft (3)>>>Qdeque ([3, 1, 2])>>>Q.pop ()2>>>Qdeque ([3, 1])>>>Q.popleft ()3
3. Find the largest and smallest n elements
The HEAPQ module has two functions: nlargest()
and nsmallest()
can solve this problem. Their return value is a list. Keyword parameters are supported.
Importheapqnums= [1, 8, 2, 23, 7,-4, 18, 23, 42, 37, 2]heapq.nlargest (3, Nums)#[All, Notoginseng, all]Heapq.nsmallest (3, Nums)#[ -4, 1, 2]Portfolio= [ {'name':'IBM','shares': 100,' Price': 91.1}, {'name':'AAPL','shares': 50,' Price': 543.22}, {'name':'FB','shares': 200,' Price': 21.09},]cheap= Heapq.nsmallest (3, Portfolio, key=Lambdas:s[' Price']) Expensive= Heapq.nlargest (3, Portfolio, key=Lambdas:s[' Price'])
Note: When the number of elements to find is relatively small, the function nlargest()
and nsmallest()
is appropriate, if you just want to find the only minimum or maximum (n=1) element, then the use min()
and max()
function will be faster, if the size of N and the size of the collection is close, It is usually faster to sort the collection before using the slice operation.
In the underlying implementation, the collection data is first sorted into a list:
>>> nums = [1, 8, 2, 7, -4,, 2]import heapq>>> heapq.h Eapify (nums)>>> nums[-4, 2, 1, 7, 2, 8,]>>> heapq.heappop ( nums)-4>>> heapq.heappop (nums)1>>> heapq.heappop (nums)2
The most important feature of a heap data structure is heap[0]
always the smallest element . And the remaining elements can be easily obtained by invoking the method heapq.heappop()
, which pops the first element out and then replaces the popup element with the next smallest element (the operation time complexity is only O (log N), N is the heap size).
3. Implement a priority queue
Each pop operation always returns the one with the highest priority.
Import HEAPQ class priorityqueue: def __init__ (self): = [] = 0 def push (self, item, priority): Heapq.heappush (self._ Queue, (-priority, Self._index, item )+ = 1 def pop (self): return Heapq.heappop (self._queue) [-1]
How to use
>>> q =Priorityqueue ()>>> Q.push ('Foo', 1)>>> Q.push ('Bar', 5)>>> Q.push ('spam', 4)>>> Q.push ('Grok', 1)>>>Q.pop ()'Bar'>>>Q.pop ()'spam'
The _queue element is the size of the tuple,tuple is compared to the first element size, if the same is compared to the next element. The _index is added to the tuple in order to differentiate the priority elements in the push order, and also to avoid the error if item does not support the comparison size. -priority the priority counter, ensuring that the smallest element function in the queue (the most important) is always placed in _queue[0]. heapq.heappush()
and the first element is heapq.heappop()
inserted and deleted separately on the queue, the _queue
first element of the _queue is always the smallest, ensuring that the queue _queue the first element with the highest priority.
Reference: "Python Cookbook" 3rd Edition
Http://python3-cookbook.readthedocs.io/zh_CN/latest/index.html
Python Learning notes-data structures and algorithms (i)