table of Contents
3. Chained comparison operators
4. Ternary operator for conditional assignment
6. Make good use of else or finally statements
7. Make good use of anonymous function lambda
1. Multi-variable assignment
a = b = c = 1
a, b, c = 1, 2, "john"
a,b,c = function1(), function2(), function3()
2. Variable exchange value
a,b=b,a
3. Chained comparison operators
result= 1< n< 20
4. Ternary operator for conditional assignment
b = 2 if a > 2 else 1
x = 10 if (y == 9) else 20
5. List comprehension
num = [1,2,3,4,5,6,7,8, 9]
new_num = [i*2 for i in num if i%2==0]
6. Make good use of else or finally statements
for ... else ... When the for loop is completed (not a break to terminate the loop), execute the else code block
while ... else .... Only when the while loop condition is false and exits (non-break terminates the while loop), execute the else code block
try ... except ... else execute else code if there is no exception
try...except...finally The finally statement will be executed regardless of whether there is an error
7. Make good use of anonymous function lambda
(1) Multiple parameters
f = lambda a,b,c: a+b+c #Equivalent to returning a+b+c
a= f(1,2,3) #result a=6
(2) Use the default value
c = lambda x,y=2: x+y
(3)*z returns a tuple
a = lambda * z: z
a('Testing1','Testing2')
Result: ('Testing1','Testing2')
(4) **arg returns a dictionary
c = lambda ** arg: arg
(5) Pass real parameters directly behind
(lambda x,y: x if x> y else y)(101,102) #返回102
(lambda x:x**2)(3) #return 9
(6) The value returned by lambda is used in combination with map, filter, and reduce
filter(lambda x:x%3==0,[1,2,3,4,5,6])
squares = map(lambda x:x**2,range(5)
a=[('b',3),('a',2),('d',4),('c',1)]
sorted(a,key=lambda x:x[0]) #Sort according to the first element
Used in conjunction with the reduce function
#!/usr/bin/python
from functools import reduce
def add(x, y): # Add two numbers
return x + y
sum1 = reduce(add, [1,2,3,4,5]) # Calculate the list sum: 1+2+3+4+5
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5]) # Use lambda anonymous function
(7) Nested use: Nest lambda functions into ordinary functions, and the lambda function itself is used as the return value
def increment(n):
return lambda x:x+n
f=increment(4)
f(2)
6
(8) String union, there is a default value, you can also use the format x=(lambda...)
x=(lambda x='Boo',y='Too',z='Z00':x+y+z)
print(x('Foo'))
'FooTooZoo'
(9) Determine whether the string starts with a certain letter
Names = ['Anne', 'Amy', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']
B_Name= filter(lambda x: x.startswith('B'),Names)
print(B_Name)
['Bob', 'Barbara']
(10) Find the sum of two list elements
a = [1,2,3,4]
b = [5,6,7,8]
print(list(map(lambda x,y:x+y, a,b)))
[6,8,10,12]
(11) Find the length of each word in the string
sentence = "Welcome To Beijing!"
words = sentence.split()
lengths = map(lambda x:len(x),words)
print(list(lengths))
[7,2,8]