Functions - multiple return values, lambdas

## The function returns multiple values:

1. If the function returns multiple values, it will put the values ​​in a tuple by default

def say():
  return 1,2,3,4

print(say()) ------------- (1,2,3,4)


2. The function returns multiple values, which can be received by multiple variables

def say():
  return 1,2,3,4

a,b,c,d = say() ------------a=1,b=2,c=3,d=4
print(a,b,c,d)

 

## Anonymous function (lambda)
function is very simple, only used once

res = lambda x:x+1 #After the colon is the function body, which is also the processing logic of the function, and before the colon is the return value

print(res(1))

Example: dictionary sort

#Dictionary is unordered, you can't sort the dictionary directly, you have to convert it to a list

d = {'a':1,'b':2,'c':3}

res = sorted(d.items(),key = lambda x:x[0])

print(res)

 

## Define the parameter type

For example: def is_float(s:str): #Specify that the parameter s is a string type, but it does not have any special effect, and other types can still be passed after the definition

Guess you like

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