1. The function has multiple return values
import xpinyin
p = xpinyin.Pinyin() #Instantiate
res = p.get_pinyin('Chen Weiliang','')
print(res)
def say():
num1 = 1
num2 = 2
num3 = 3
return num1,num2,num3
res1, res2, res3 = say() #You can also accept multiple variables when returning
Functions return multiple values:
1. If the function returns multiple values, it will put these values into a tuple
2. If the function returns multiple values, it can also be received by multiple variables
2. Anonymous function , this function is very simple and only used once
Lambda
Such as res = lambda x: x+1 # can only handle some simple logic
lambda
anonymous function
lambda x: x+1 #The function body after the colon is also the processing logic of the function, and the return value before the colon
3. Selection of red balls in homework, list generation
import random
red_num = random.sample(range(1,34),6)
new_num = [ str(num) .zfill(2) for num in red_num ] #List production zill() is a string method
#
for num in red_num:
tmp=str(num).zfill(2)
new_num.append(tmp)
#
Other list generation l = [ i for i in range(1,101,2) ] #Generate odd numbers within 100, exchange space for time
#l2 = ( i for i in range(1,101,2) ) #Generate odd numbers within 100 #
#If there are parentheses outside , it is not a list, it is a generator ,
#Generator saves memory than list. It calculates an element according to the rules every time it loops and puts it in memory
#list It is to put all the elements in memory
4. Ternary expressions
a = 5
b = 4
# c = a if a > b else b # If a is greater than b, c = a, otherwise c = b, if you don't use the ternary operator, you have to write
if a > b as follows:
c = a
else:
c = b
c = a if a > b else b #The ternary expression is cyclically judged and assigned as above
5. The generator is more space
-saving ( i for i in range(1,101,2) ) than
【i for i in range(1,101,2) 】