Six Musketeers
A line of six musketeers: three functions: Map filter reduce + lambda slice deduction list
Python's most distinctive line of code, all code can borrow one line of code (target)
1.map (function, list, or string) #字符串或者列表中每个字符或每个元素都带入函数运算
1.map function:
Output as List
1) The map operation of the list element,
>>> map (s,[1,2,3])
[2, 3, 4]
2) The map operation of the string element, the function is implemented with lambda
>>> Map (Lambda X:x.upper (), "ABC")
[' A ', ' B ', ' C ']
3) function customization, apply custom function to output each element in a list or string,
Example: Custom Function Map
>>> def uppercase (s):
... if s>= ' A ' and s<= ' Z ':
.. return S
.. else:
... return ""
...
>>> print "". Join (Map (uppercase, "Aabbaban"))
Aabban
Example: Use the map function to remove lowercase letters from a string, for example: "Aabbaabb",
Result returned "AABB"
def delete_lowercase (s):
If s>= ' a ' and s<= "Z":
Return ""
Else
return s
Print "". Join (Map (delete_lowercase, "Aabbaabb"))
>>> "". Join ([I for I in map (lambda x: (Re.match (R "[acdefghijklmnopqrstuvwxyz]*], X). Group ())," ASDASD ") if i!=" " ])
' ASD ',
2.filter two parameters (custom function name, list) filter output for elements in a list
Filter instance:
>>> def uppercase (s):
... if s>= ' A ' and s<= ' Z ':
.. return S
.. else:
... return ""
...
>>> print "". Join (Map (uppercase, "Aabbaban"))
Aabban
>>> print "". Join (Filter (uppercase, "AABBABFN"))
Aabbfn
>>>
Instance:
Filter (lambda x:x in String.uppercase, "AAAASSBB")
Reduce (lambda x,y:x+y,range (1,101))
3. Reduce (function name, list) to accumulate elements in the list one by one
Accumulation
>>> print reduce (lambda x,y:x+y,range (1,101))
5050
Factorial
>>> print reduce (lambda x,y:x*y,range (1,5))
24
>>> print reduce (lambda x,y:x*y,range (1,7))
720
Instance:
list_a=[1,1,1,3,5,6,8]
Func=lambda x,y:x if y in x else x + [y]
Print reduce (func,[[],]+list_a)
4.lambda function, variable: operation expression: Outputs a variable after it is calculated as an operation expression
Syntax: variables: arithmetic expressions such as x:x+1
Reference: Function name (variable assignment) a (1)
>>> A=lambda x:x+1
>>> A (4)
5
>>> A=lambda x, Y, Z: (x+y) *z
>>> A (1,1,4)
8
>>> A=lambda x:s*x
>>> S=1
>>> A (5)
Two parameter lambda functions
Import string
fp = open ("E:\\1.txt", "W")
Content=map (Lambda x,y:x+ "," +str (y) + "\ n", List (string.lowercase), Range (1,27))
Fp.writelines (content)
list_a=[1,1,1,3,5,6,8]
Func=lambda x,y:x if y in x else x + [y]
Print reduce (func,[[],]+list_a)
5. Derivation list result expression + range + condition
[Str (a) *i for I in Range (1,times+1)]
Instance: changes each element in the list to a repeating string, such as 1 to a 2 to AA 3 to AAA
A=int (raw_input ("Input a Value:"))
Times=int (raw_input ("Input count Times:"))
Print U "sum is:", eval ("+". Join ([Str (a) *i for I in Range (1,times+1)]))
string conversion followed by + merge with Eval to sum
The list derivation is a python-based, easy-to-use, yet very important feature, and one of the most popular Python features, and it can be said that mastering it is the basic standard for becoming a qualified Python programmer. In essence, a list deduction can be understood as a function that sets up the transformation and filtering functions, which transforms a list into another list. Note is another new list, and the original list remains unchanged.
See Example:
(1) Cubic operation for each element in the list (transform function)
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [x * * 3 for x in a]
Print (a)
Print (b)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
(2) cubic operation of an even-numbered element in the list (transform function with filter condition)
a= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [x * * 3 for X in a if x% 2 = = 0]
Print (b)
[8, 64, 216, 512, 1000]
It can be seen from the results that the filter is first filtered and then transformed, that is, the element that does not satisfy the condition is first sifted out, and then the transformation operation is performed. You can add multiple filters at the same time, such as cubic operations on an even-numbered element that is greater than 5, as shown in the following example:
a= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [x * * 3 for X in a if x 2 = = 0 if x > 5]
Print (b)
[216, 512, 1000]
(3) combined with zip
A new list is formed by combining the relative due values in a A, B, two list. For example, a list that contains an x-coordinate and a list of y-coordinates form a corresponding point coordinate [x, Y] list.
a= [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
XY = [[x, Y] for x, y in Zip (A, b)]
Print (XY)
[[-1, 1], [-2, 2], [-3, 3], [-4, 4], [-5, 5], [-6, 6], [-7, 7], [-8, 8], [-9, 9], [10, 10]]
(4) Support multi-layer for loop
Converts a nested list to a one-dimensional list.
a= [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [J for I under a for J in I]
Print (b)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Python also has a dictionary derivation, set deduction, and so on, and the use of the list deduction is roughly the same way.
The use of the list deduction is very extensive, from the actual experience, the list deduction uses the frequency is very high, is also quite useful. For the list of the derivation of the multi-layer for loop, especially more than 3 layers or with complex filter conditions, the sacrifice of more readability, directly with a number of ordinary for loop implementation can be, after all, convenient implementation of the function is the first, more than a few lines of code more than a few lines.
Example: Yang Hui triangle:
#coding =utf-8
def yhtriangle (n):
L=[1]
Print L
While n>0:
L=[1]+[x+y for x, y in Zip (l[:],l[1:])]+[1]
N-=1
Print L
Yhtriangle (10)
6. Slicing
The slice syntax is as follows:
S[begin:end:stride]
In contrast to the simple slice syntax, the extended slice simply adds a 3rd parameter, the step parameter (commonly referred to as "stride" or "step" in the English material).
The "stride" parameter introduced by the extended slice syntax is a parameter that requires special attention, because its positive/negative values will affect the direction of the slice operation's access to the source sequence s, which is why the first few examples of this article may be confusing to novice python.
In fact, the rules are very simple, it is not worth a penny:
1) When the STRIDE parameter is positive (positive), it indicates that the slice operation accesses the elements of the source sequence s from left to right (that is, forward), and that the Python interpreter defaults to none when the begin and end parameters are defaulted. If s[0:: 1] will be interpreted as s[0:none:1], the end actually takes a value greater than the upper limit of its valid index range to ensure that the slice operation can access all the elements from the start of the source sequence s (left to right).
2) When the Stride parameter is negative (negative), it indicates that the slice operation accesses the elements of the source sequence s from right to left (that is, reverse), and that the Python interpreter defaults to none if the begin and end parameters are defaulted. such as s[-1::-1] will be interpreted as S[-1:none:-1], at this point, the actual value of end is less than the lower limit of its valid index range, has ensured that the tile operation can access to the source sequence s from begin all elements (reverse, right-to-left).
3) the start and end index values of the slice expression need to be guaranteed to be in the direction of access for the slice operation, regardless of whether the stride parameter is positive or negative, and there is an element between begin and end, so that the slice operation is guaranteed to return a non-empty set.
s[4,8,1]
Slice instance:
Import OS
Os.system ("Ls-al > A.txt")
With open ("A.txt") as FP:
For I in FP:
If "1.py" in I:
Print I.split () [-2] #倒数第二位
Break
>>> l=[1,2,3,4,5,6]
>>> l[:]
[1, 2, 3, 4, 5, 6]
>>> l[1:]
[2, 3, 4, 5, 6]
l[:]
L[1:]
A word on the Python six Musketeers