Chapter VIII, the dictionary function Advanced Formula and anonymous functions

Chapter VIII, the dictionary function Advanced Formula and anonymous functions

A, Dictionary zip conjunction with the general formula

压缩后的每一个元素是元组类型的
keys=["name","age","gender"]
values=["nick",19,"male"]
res=zip(keys,values)
for i in res:
    print(i)
    print(type(i))
print(res)
('name', 'nick')
<class 'tuple'>
('age', 19)
<class 'tuple'>
('gender', 'male')
<class 'tuple'>
<class 'zip'>

Second, the anonymous function

1. What is the function

Anonymous function is to function without a name, will be used once recovered, can run in brackets

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

2. in conjunction with the built-in functions

storted (): the containers from small to large

salary_list_dict = {'tank':2,'nick':5,'sean':8}
salary_list = list(salary_list_dict.items())#变为列表
print(sorted(salary_list,key = lambda i:i[1])) #把salary_list变成迭代器,取出所有元素i,i[1]就是元组的第二个值
[('tank', 2), ('nick', 5), ('sean', 8)]
salary_list_dict = {'tank':2,'nick':5,'sean':8}
salary_list = list(salary_list_dict.items())
print(list(map(lambda i:i[1] + 2000,salary_list)))   #让他们的工资都加2000
[2002, 2005, 2008]
salary_list_dict = {'tank':2,'nick':5,'sean':8}
salary_list = list(salary_list_dict.items())
print(list(filter(lambda i:i[1] <6,salary_list)))  #输出薪资小于6的人名
[('tank', 2), ('nick', 5)]

Works :

  1. First iterables become iterator object

  2. The i as parameters to the function specified by the first parameter, then the judging function built-in method

Guess you like

Origin www.cnblogs.com/demiao/p/11348959.html