Python's small functions can improve efficiency, usually in the work often ignore these content, and the use of a very primitive rough method of writing code; After writing for a period of time, found that their own improvement is very little, to write a small script also have to tangle half a day, and those danale difference is too big, so to review their own, See how you can improve your technical skills in that area;
Today I'll start by learning about Python's practical small functions:
Lamda () returns a function expression, similar to Def, but lighter than Def, can have no name
Add_by_lambda = Lambda X,y:x+yprint add_by_lambda (1, 1) can even be directly appended to the argument directly to get the return value, such as Lambda x,y:x+y, 1, 1 Returns the result is 2----------- --------------------------def add (x, y): Return x+yprint Add (1, 1)
Zip ()
Definition:zip ([seql, ...]accepts a series of iterative objects as parameters , packages the corresponding elements in the object into tuple (tuples), and returns a list of these tuples ). If the length of the passed parameter is not equal, the length of the returned list is the same as the object with the shortest length in the parameter.
1 >>> z1=[1,2,3] 2 >>> z2=[4,5,6] 3 >>> result=zip (Z1,Z2)
The zip () Mate * operator allows you to unzip a list object that has already been zipped, splitting the merged sequence into multiple tuples.
1 >>> Zip (*result) 2 [(1, 2, 3), (4, 5, 6)]
The built-in functions associated with the sequence are: sorted (), reversed (), enumerate (), Zip ()
Sorted () and zip () return a sequence (list) object
Reversed (), enumerate () returns an iterator (similar to a sequence)
Http://www.cnblogs.com/BeginMan/archive/2013/03/14/2959447.html
Scene:
* Two-dimensional matrix transformation (matrix of the row and column interchange)
A = [[1], 2, 3], [4, 5, 6], [7, 8, 9]] zip (*a) [(1, 4, 7), (2, 5, 8), (3, 6, 9)]map (List,zip (*a)) [[1, 4, 7], [2, 5, 8], [3 , 6, 9]]
* Sequential acquisition of data
>>> name= (' Jack ', ' Beginman ', ' Sony ', ' Pcky ') >>> age= (2001,2003,2005,2000) >>> for a,n in zip (name,age): Print a,n output: Jack 2001beginman 2003sony 2005pcky 2000
Zip Advanced Applications:
1.zip Package unpacking list and multiples >>> a = [1, 2, 3]>>> b = [' a ', ' B ', ' C ']>>> z = zip (a, b) >>> z[(1, ' a '), (2, ' B ') ), (3, ' C ')]>>> zip (*z) [(1, 2, 3), (' A ', ' B ', ' C ')]2. Use Zip to merge adjacent list items >>> a = [1, 2, 3, 4, 5, 6]>>> zip ( * ([ITER (a)] * 2)] [(1, 2), (3, 4), (5, 6)]>>> group_adjacent = lambda a, k: zip (* ([ITER (a)] * k)) >>> group_adjacent (A,  3) [(1, 2, 3), (4, 5, 6)]>>> group_adjacent (a, 2) [(1, 2) , (3, 4), (5, 6)]>>> group_adjacent (a, 1) [(1,), (2,), (3,), (4,), (5,), (6,)]>>> zip (A[::2], a[1::2]) [(1, 2), (3, 4), (5, 6)]>>> zip (A[::3], a[1::3], a[2::3]) [(1, 2, 3), (4, 5, 6)]>> > group_adjacent = lambda a, k: zip (* (a[i::k] for i in Range (k)) >>> group_adjacent (a, 3) [(1, 2, 3), (4, 5, 6)]>> > group_adjacent (A, 2) [(1, 2), (3, 4), (5, 6)]>>> group_ Adjacent (a, 1) [(1,), (2,), (3,), (4,), (5,), (6,)]3. Use zip and iterators to generate sliding window ( N -grams) >>> from itertools import islice>>> def n_ Grams (a, n):... z = (Islice (a, i, none) for i in range (n)) ... return zip (*z) ...>>> a = [1, 2, 3, 4, 5, 6]>>> n_grams (A, 3) [(1, 2, 3), (2,  3, 4),   (3, 4, 5), (4, 5, 6)]>>> n_grams (a, 2) [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]>>> n_grams (a, 4) [(1, 2 , 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]4. Using the zip inversion dictionary >>> m = {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}>>> M.items () [(' A ', 1), (' C ', 3), (' B ', 2), (' d ', 4)]>>> zip ( M.values (), m.keys ()) [(1, ' a '), (3, ' C '), (2, ' B '), (4, ' d ')]>> > mi = dict (Zip (m.values (), m.keys ())) >>> mi{1: ' A ', 2: ' B ', 3: ' C ', 4: ' d '}
Filter ()
The filter function accepts two parameters, Func and list, and, after filtering, returns a list where the Func function object can only have one incoming parameter. The principle is to pass the list of all elements as parameters to the function func, return the list of elements that can cause Func to return true, and if Func is None, the default Python built-in identity function is used to directly determine the element's true or False.
For example:
A = [1,2,3,4,5,6,7] B=filter (Lambda x:x>2, a) print b# filter odd set a = [1,2,3,4,5,6,7] B=filter (Lambda x:x%2, a) print B
Map ()
The map function is a powerful mapping function that passes through two parameters, one is Func, the other is list, and the effect is that Func acts on each element of a given sequence and provides a return value using a list. For example:
a=[0,1,2,3,4,5,6,7] Map (Lambda x:x+3, a) a=[1,2,3] b=[4,5,6] Map (Lambda X,y:x+y, A, b) [5,7,9] #my_map函数实现def My_map (func , *args): Return [func (ARG) for Arg in args]
Reduce ()
The reduce function passes in the parameter Func and list, which traverses the list element and calls the Func function to accumulate, the effect is:
Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)
Examples of use are:
#str to int
def str2int (s):
return reduce (lambda x,y:x*10+y, map (int, s))
Magical Highlights: http://devopstarter.info/pythonkai-fa-zhi-mapreduce/
#两个list, take (x-y) + (y-x)
X=[{' A ': 1, ' B ': 2}, {' C ': 3}, {' d ': 4}]
Y=[{' a ': 1}, {' C ': 3}, {' E ': 5}]
Filter (lambda z: (x+y). Count (z) <2, (x+y))
#flatten out nested sublist
#result: [1, 2, 3, 4, 5]
Import operator
Reduce (Operator.concat, [[1, 2], [3, 4], [], [5]], [])
#多项式求和
Import operator
def evaluate (A, X):
Xi = map (lambda i:x**i, range (0, Len (a)))
Axi = Map (Operator.mul, A, xi)
return reduce (operator.add, Axi, 0)
#数据库SQL
Reduce (max, map (camera.pixels, filter (
Lambda C:c.brand () = = "Nikon", cameras)))
#maybe equals
SELECT Max (pixels)
From cameras
WHERE brand = "Nikon"
#There.
#cameras is a sequence
#where clause is a filter
#pixels is a map
#max is a reduce
#一行并发
Import Urllib2
From Multiprocessing.dummy import Pool as ThreadPool
URLs = [
' Http://www.python.org ',
' Http://www.google.com ',
' Http://www.baidu.com ',
' http://www.python.org/community/',
' Http://www.saltstack.com '
]
#pool = ThreadPool ()
Pool = ThreadPool (4) # Sets the pool size to 4
result = Pool.map (Urllib2.urlopen, URLs)
Pool.close ()
Pool.join ()
int () to number int (' 0 ')
Str () to String str (2)
Lower () Turn lowercase lower (Windows)
Upper () turn capital Upper (Linux)
ITER ()
List.count (' AAA ') counts the number of occurrences of AAA in the list
This article is from the "justification is excuse" blog, please make sure to keep this source http://joylee.blog.51cto.com/1357577/1789627
Python inline functions