lambda, list production, dictionary to list sorting

1. The function returns multiple values:

  1 ) If the function returns multiple values, it will put the returned values ​​in a tuple

def say():
    num1 = 1
    num2 = 2
    num3 = 3
    return num1,num2,num3
res = say()
print(res)

>>> (1, 2, 3)

  2) If the function returns multiple values, you can use multiple variables to receive them separately

def say():
    num1 = 1
    num2 = 2
    num3 = 3
    return num1,num2,num3
res1,res2,res3 = say()
print(res1)   #>>>1
print(res2)   #>>>2
print(res3)   #>>>3

 

2, lambda : anonymous function, the function is very simple, only used once, no need to define

 

res = lambda x:x+1   #The return value is before the colon, and the function body is after the colon, which is also the processing logic of the function 
print (res(1 ))

>>> 2

 

 

3. List Compilation (List)

l = [i for i in range(1,101,2)]

l = [i for i in range(1,101) if i%2==1]   #Or write 
print (l)

>>>[1, 3, 5, 7, 9...]

 

If the outside of the list comprehension is in the form of (): l is not a list , but a generator

l = (i for i in range(1,101) if i%2==1 )
 print (l)   # l is a generator

# print(l.__next__()) #Generator calls take one value at a time

for i in l:   
    print(i)

>>> <generator object <genexpr> at 0x00BFD8C8>
>>>1 3 5 7 9...

#The generator will calculate only one element according to the rules each time it loops, put it in memory, save memory than list

#list is to put all elements in memory

 

4. Ternary expressions

a = 5 
b = 4 
c = a if a>b else b    #ternary expression 
print (c)

Without ternary expressions it is as follows:

a = 5
b = 4
if a>b:
    c = a
else:
    c = b
print(c)

 

5. The dictionary is unordered, and there is no direct sorting of the dictionary. First convert the dictionary to a list and then sort

#sorted() : Take the elements in the two-dimensional array automatically each time

d = { ' a ' :5, ' b ' :2, ' c ' :3 }
 print (d.items()) #Get     a two-dimensional array 
res = sorted(d.items(),key= lambda x: x[0]) # key=key value of dictionary, sort 

res = sorted(d.items(),key= lambda x:x[1])   #sort according to the value of dictionary 
print (res)

>>> dict_items([('b', 2), ('a', 5), ('c', 3)])
>>> [('a', 5), ('b', 2), ('c', 3)]

 

Take multiple while looping:

l = [ [1,2,3],[3,4,5],[5,6,7 ] ]
 for a,b,c in l:   # a,b,c are 3, the small list above Each also contains 3 elements? 
    print (a,b,c)

 

6. When defining a function, tell others what type of parameters should be passed

def is_float(s:str):
    pass

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325342667&siteId=291194637