The first chapter data structure and algorithm
1.1 Splitting a sequence into separate variables
Applies to tuples, lists, strings, and so on. A decomposition operation can be performed as long as it is an object that can be iterated. The only requirement is that the total number and structure of the variables be the same as the sequence.
1.2 Explode elements from an arbitrary length of an iterative object
"* expression"
The following code is used in the "*args", if you remove the *, will be an error.
Records = [('foo', '), ('bar','Hello '), ('foo', 3,4)] for in Records: Print(Tag,*args)
The split operation, combined with split, enables very useful features:
' nobody:*:-2:-2:unprivileged User:/var/empty:/usr/bin/false ' uname,*fields,homedir,sh = Line.split (':')
1.3 Keep last n elements
The code below is not specifically understood , and the generator is unfamiliar.
fromCollectionsImportdequedefSearch (lines,pattern,history): Previous_lines= Deque (maxlen=History ) forLineinchlines:ifPatterninchLine :yieldline,previous_lines previous_lines.append (line)if __name__=='__main__': With open ('Somefile.txt') as F: forLine,prevlinesinchSearch (F,'Python', 5): forPlineinchPrevlines:Print(pline,end="') Print(line,end="') Print('-'*20)
Deque (maxlen=n) creates a fixed-length queue that automatically deletes the oldest records when new elements are added.
When you do not specify a length, create a queue with no bounds:
from collections import Dequeq = Deque () q.append ( 1 ) q.append ( 2 3" print (q) q.append ( 4) # Right add element q.appendleft (0) # add element to left print (q) q.pop () # print (q) q.popleft () # print (q)
1.4 Finding the largest or smallest n elements
Nlargest and Nsmallest functions in the HEAPQ module:
Import= [1,8,2,23,7,-4,16,23,42,37,2]print(heapq.nlargest (3, nums)) Print(Heapq.nsmallest (3,nums))
Provide a parameter key to work on a more complex structure:
Portfolio = [{'name':'IBM','shares': 100,' Price': 91.1}, {'name':'AAPL','shares': 50,' Price': 543.22}, {'name':'FB','shares': 200,' Price': 21.09}, {'name':'HPQ','shares': 35,' Price': 31.75}, {'name':'YHOO','shares': 45,' Price': 16.35}, {'name':'ACME','shares': 75,' Price': 115.65}]cheap= Heapq.nsmallest (3,portfolio,key=Lambdas:s[' Price'])Print(cheap) expensive= Heapq.nlargest (3,portfolio,key=Lambdas:s[' Price'])Print(expensive)
If you are looking for the largest or smallest n elements, and n is small compared to the total number of elements in the collection, you can use the following function (better performance): why?
Nums = [1,8,2,23,7,-4,16,23,42,37,2= list (nums)# finds the 3rd small element Heapq.heappop ( Heap) Heapq.heappop (heap) Heapq.heappop ( heap)
The nlargest and Nsmallest functions are most appropriate when the number of elements to be searched is relatively small. If you simply look for the maximum and minimum values, then the Max and Min functions will be faster. If N is the same size as the collection itself, it is usually quicker to sort the collection first and then slice the operation (sorted (items) [: N] and sorted (items) [-N:]).
1.5 Implementing a priority queue (pending)
1.6 mapping keys to multiple values in a dictionary
One-click Multi-valued dictionary, you can use the Defaultdict class in the Collections module:
fromCollectionsImportDEFAULTDICTD=defaultdict (list) d['a'].append (1) d['a'].append (2) d['b'].append (3)Print(d) d=defaultdict (set) d['a'].add (1) d['a'].add (2) d['b'].add (3)Print(d)
Use a list or a collection, depending on the actual needs, focus on the order, use lists, and if you want to remove duplicate values, use the collection.
The above method automatically creates a dictionary table entry for later access, or you can use the SetDefault method on a normal dictionary:
D = {}d.setdefault ('a', []). Append (1) d.setdefault ('A ', []). Append (2) d.setdefault ('b', []). Append (3) Print (d)
1.7 Keep the dictionary in order
Pythoncookbook Reading notes