Data structures and algorithms cookbook_

1.1 the data into separate variable
= 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)
 # using an equal number of parameters to receive 


_, B, C, D, E, F, G, H, _ = list_a 
 Print (B, C, D, E, F, G , H)
 # Do not use variable data with no reception
View Code

 

1.2 iterables elements from the decomposition of any length

Use * XXX achieve

list_a = Range (20 is ) 
First, * Middle, Last = list_a
 Print (First, Middle, Last)
 # using * to receive any number, or even no, returns a List 

# when a flag bit in a neuron progenitor time, a better application 
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)
View Code

 

1.3 saves the last N elements

collections.deque ()

Import Collections 

# use collections.deque (maxlen = 5) to define a fixed-length list, if there has been reached the maxlen, automatically delete the oldest data is inserted new data is written 
DEF Search (Lines, pattern, History =. 5 ): 
    previous_lines = collections.deque (= the maxlen History)
     for Line in Lines:
         IF pattern in Line:
             the yield Line, previous_lines 
        previous_lines.append (Line) 

IF  the __name__ == " __main__ " : 
    with Open ( " test.txt " , " R & lt " , 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 use Description 
# a stronger 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])
View Code
 
1.4 find the maximum or minimum of N elements

heapq.nlargest(),heapq.nsmallest()

Import heapq 

the nums = [5,56,7,6,34,2,5,7,6,89,80, -90,0,9, -67,5,45 ,] 

Print (min (the nums))
 Print (max (the nums)) 

Print (heapq.nlargest (. 3 , the nums))
 Print (heapq.nsmallest (. 3 , the nums)) 

# can support 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']))
View Code

 

 

1.5 implement priority queue

heapq.heappush(),heapq.heappop()

import heapq


#列表中实际存一个元组,(-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())
View Code
 
1.6 in dictionary will be mapped to a plurality of key values

collections.defaultdict(list),collections.defaultdict(set)

Import Collections 

D = collections.defaultdict (List) # automatic initialization, determines whether there is no 
D [ " A " ] .append (. 1 ) 
D [ " A " ] .append (. 1 ) 
D [ " A " ] .append (. 1 ) 
D [ " A " ] .append (. 1 )
 Print (D [ ' A ' ])
View Code

 

1.7 Let dictionary to keep order

collections.OrderedDict()

Import Collections 

D = collections.OrderedDict () # twice the normal dictionary, should not use large data 
D [ ' foo ' ]. 1 = 
D [ " bar " ] = 2 
D [ " from spam " ] =. 3 
D [ " Gork " ] =. 4
 for I in D:
     Print (I)
View Code

 

1.8 Calculation and dictionary-related

zip(),min(),sorted().max()

# Dictionary are used when the size of the operation key value is compared to the size, and we want to compare with the value generally value, but also want to get the key value 

Prices = {
     " ACME " : 23 is ,
     " AAPL " : 345 ,
     " the IBM " : 34 is ,
     " the FB " : 24 
} 

# use zip, zip returns an iterator, only once 

MIN_PRICE = min (ZIP (prices.values (), prices.keys ()))
 Print (MIN_PRICE) 

# ordering 
= price_sorted the sorted (ZIP (prices.values (), prices.keys ()))
 Print (price_sorted)
View Code

 

 
1.9 look for similarities in the two dictionaries

 

= A {
     " X " : 2 ,
     " Y " :. 5 ,
     " Z " :. 7 
} 

B = {
     " X " : 2 ,
     " Y " :. 8 ,
     " W " :. 4 
} 

Print (a.keys () & b.keys ()) # find the same Key 
Print (a.keys () - b.keys ()) # find a b, there is no Key 
Print (a.items () & b.items ()) # looking for the same item
View Code

 

 

1.10 removing duplicates from the sequence and the sequence remains unchanged between elements
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)
View Code

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/jiaojianglong/p/11260093.html