10-Python-map&filter

map:

(图片引用自wupeiqi)

 

 代码示例:

 1 #现有列表list1 = [11,22,33,44],要求列表中的每个元素都增加100
 2 list1 = [11,22,33,44]
 3 tmp_list = map(lambda x:x+1 , list1) #map函数的第一个参数为函数,循环第二个参数
 4 new_list = list(tmp_list)
 5 print(new_list)
 6 
 7 #使用自定义函数
 8 def func(x):
 9     return x+100
10 
11 tmp_list1 = map(func,list1)
12 new_list1 = list(tmp_list1)
13 print(new_list1)


 

filter:

(图片引用自wupeiqi)

 代码示例:

 1 #现有列表list2 = [11,22,33,44,55],现要求列表中大于33的值构建一个新列表
 2 
 3 list2 = [11,22,33,44,55]
 4 
 5 def func(x):
 6     if x > 33:
 7         return True
 8     else:
 9         return False
10 
11 tmp_list = filter(func,list2)
12 new_list = list(tmp_list)
13 print(new_list)

 

posted @ 2017-10-13 16:58  Druid_Py  阅读(226)  评论(0编辑  收藏  举报