1.1 Decomposition of data into separate variables
list_a = [1,2,3,4,5,6,7,8,9] a,b,c,d,e,f,g,h,i = list_a print(a,b,c,d,e,f,g,h,i) #Receive with an equal number of parameters _,b,c,d,e,f,g,h,_ = list_a print(b,c,d,e,f,g,h) #Do not use a useless variable to receive data
1.2 Decomposition of Elements from Iterative Objects of Arbitrary Length
Implement with * XXX
list_a = range(20) first,*middle,last = list_a print(first,middle,last) #Use*To receive any number, or even none, and return one list #A better application when there is a marker in a meta-ancestor records = [ ("foo",1,2), ("bar","hello"), ("foo",3,4) ] def do_foo(x,y): print("foo",x,y) def do_bar(s): print("bar",s) for tags,*args in records: if tags == "foo": do_foo(*args) elif tags == "bar": do_bar(*args)
1.3 Save the last N elements
collections.deque()
import collections #Use collections.deque(maxlen=5)To define a fixed length list,If new data has been written when it has been reached maxlen,Automatic deletion of the earliest inserted data def search(lines,pattern,history = 5): previous_lines = collections.deque(maxlen=history) for line in lines: if pattern in line: yield line,previous_lines previous_lines.append(line) if __name__ =="__main__": with open("test.txt","r",encoding="utf8") as f: for line,previous in search(f,"python",5): for pline in previous: print(pline,end="") print(line,end="") print("-"*20) #collections.deque Introduction to Use #A more powerful list queue = collections.deque(["jiao","li",'hao',"yu"]) queue.appendleft("wu") print(queue) queue.append("haha") print(queue) queue.popleft() print(queue) print(queue[4])
1.4 Find the largest or smallest N elements
heapq.nlargest(),heapq.nsmallest()
import heapq nums = [5,56,7,6,34,2,5,7,6,89,80,-90,0,9,-67,5,45,] print(min(nums)) print(max(nums)) print(heapq.nlargest(3,nums)) print(heapq.nsmallest(3,nums)) #Support for more complex data structures portfolio = [ {"name":"jiao","age":24}, {"name":"jsdfo","age":2}, {"name":"jisd","age":12}, {"name":"jdo","age":36}, {"name":"li","age":25}, {"name":"jgd","age":50}, ] print(heapq.nlargest(3,portfolio,key=lambda s:s['age'])) print(max(portfolio,key=lambda s:s['age']))
1.5 Implementing Priority Queue
heapq.heappush(),heapq.heappop()
import heapq #A tuple is actually stored in the list.-priority,self._index,item) class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self,item,priority): heapq.heappush(self._queue,(-priority,self._index,item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1] def get(self): return self._queue q = PriorityQueue() q.push("foo",2) q.push("sdf",3) q.push("sfasc",5) q.push("fdsg",4) print(q.pop()) print(q.get())
1.6 Mapping keys to multiple values in a dictionary
collections.defaultdict(list),collections.defaultdict(set)
import collections d = collections.defaultdict(list)#Automatic initialization without judging whether it exists d["a"].append(1) d["a"].append(1) d["a"].append(1) d["a"].append(1) print(d['a'])
1.7 Keep dictionaries in order
collections.OrderedDict()
import collections d = collections.OrderedDict()#Big data shouldn't be used twice as much as regular Dictionaries d['foo'] = 1 d["bar"] = 2 d["spam"] = 3 d["gork"] = 4 for i in d: print(i)
1.8 Computational Problems Related to Dictionaries
zip(),min(),sorted().max()
#Dictionaries are used for size operations. key Values are compared in size, and we generally want to use value Value comparison, but also want to get the value of key prices = { "ACME":23, "AAPL":345, "IBM":34, "FB":24 } #utilize zip,zip Returns an iterator that can only be used once min_price = min(zip(prices.values(),prices.keys())) print(min_price) #sort price_sorted = sorted(zip(prices.values(),prices.keys())) print(price_sorted)
1.9 Find similarities in two dictionaries
a = { "x":2, "y":5, "z":7 } b = { "x":2, "y":8, "w":4 } print(a.keys() & b.keys())#Look for the same key print(a.keys() - b.keys())#Seek a There are b None of them. key print(a.items() & b.items())#Find the same item
1.10 Remove duplicates from the sequence and keep the order between elements unchanged
def dedupe(items,key = None): seen = set() for item in items: val = item if key is None else key(item) if val not in seen: yield item seen.add(val)