1. Functions that 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
def say(): num1 = 1 num2 = 2 num3 = 3 return num1,num2,num3 print ( say()) #If the function returns multiple values, it will put these values into a tuple, (1, 2, 3 ) res1,res2,res3 = say() #When multiple values are returned, multiple variables can be used to receive print (res1) # 1 print (res2) # 2 print (res3 ) # 3
2. List Compilation
l = [i for i in range(1,101,2)]
List comprehensions, which can only be used in lists
Write the loop first, then take out the i in the loop, you can do some simple operations (zero-fill, convert to string, etc.)
import random red_num = random.sample(range(1,34),6) new_num = [] # for num in red_num: # tmp = str(num).zfill(2) # new_num.append(tmp) new_num = [str(num).zfill(2) for num in red_num]#列表生成式 print(new_num)#['16', '20', '07', '18', '13', '01']
Generate odd numbers up to 100
l = [i for i in range(1,101,2)] #The outside is [] is a list print (l)
3. Generator
l1 = (i for i in range(1,11,2))
Replace the [ ] in the list comprehension with ( ), and printing the generator itself will display the generator instead of the list
l = [i for i in range(1,11,2)] #The outside is [] is a list #The space is exchanged for time, the memory usage is large, but there is no need to calculate the cpu #list It is to put all the elements In the memory, 5 memory spaces will be applied here print (l) # [1, 3, 5, 7, 9] l1 = (i for i in range(1,11,2)) #outside is () If it is generator # generator generator saves memory than list, it calculates an element according to the rules each time it loops, and puts it in memory # generator performance is better than list, only applies for one piece of memory space, each time Call and calculate according to the rules print (l1) # <generator object <genexpr> at 0x00000000030FE4C0> for i in l1: print (i) #1 3 5 7 9
4. Ternary expressions
c = a if a > b else b
a = 5 b = 3 # if a > b: # c = a # else: # c = b c = a if a > b else b # if a is greater than b, a = c, otherwise c = b print (c )
Five, loop two-dimensional array
l = [ [1,2,3,4], ['a','b','c','d'] ] for a,b,c,d in l: #There are multiple elements in the two-dimensional array, you can loop like this print (a) # 1,a print (b) # 2, b
6. Declaration input format
Just for code readability and does not cast types
def my(name:str): #Tell others that name is str, but it will not be forced to convert, l:list tells others that the input is list print (name) my('hello') my([ ' 123 ' ,123]) #The input parameter can also be a list, ['123', 123]