8.13 anonymous function

8.13 anonymous function

A named function

Function function name used is based.

def func():
    pass
func()

Anonymous function

Anonymous function, he has no name binding, ie, once recovered, either bracketed run.

print(lambda x,y: x+y)
# <function <lambda> at 0x0000028D950DC158>

res = lambda x,y:x+y
print(res(1,2))
# 3

Built-in function in combination with

Generally anonymous functions max (), sorted (), filter (), sorted () method in combination.

salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}

1. If we want to remove the highest-paid people from the dictionary, we can use the max () method, but the max () the comparison is the default dictionary key.

  1. First iterables become iterator object
  2. res = next (iterator object), the parameters passed to the function key res as specified, and returns the value as determined according to the function
print(max(salary_dict,key=lambda k:salary_dict[k]))  # jason

2. If we want the dictionary in the above-mentioned people descending order according to salary, you can use the sorted () method.

sorted () works:

  1. First iterables become iterator object
  2. res = next (iterator object), res as the argument to the function specified by the first parameter, and returns the value as determined according to the function.
print(sorted(salary_dict,key=lambda k:salary_dict[k])) 
# ['sean', 'nick', 'tank', 'jason']

3. If we want a list of names to do a deal, you can use the map () method.

map () works:

  1. First iterables become iterator object
  2. res = next (iterator object), res as the argument to a function specified by the first parameter, and then returns as one map () method of the function result value.
lis = ['jason', 'tank', 'sean']
res = map(lambda name:f'{name} sb',lis)
print(list(res))
# ['jason sb', 'tank sb', 'sean sb']

4. If we want to filter contains the name of the name 'sb' in addition, we can use the filter () method.

filter () works:

  1. First iterables become iterator object
  2. res = next (iterator object), as a function of the res parameters specified by the first parameter passed, then the filter will determine the return value of the function is true, if true left.
lis = ['jason sb', 'tank sb', 'sean sb','nick']
res1 = filter(lambda i:i.endswith('sb'),lis)
print(list(res1))
# ['jason sb', 'tank sb', 'sean sb']

Guess you like

Origin www.cnblogs.com/dadazunzhe/p/11348828.html