問題舉例:html
過濾列表[1, 2, 5, -1, 9, 10]中的負數python
篩選字典{「zhangsan」:97, "lisi":80, "wangwu":60, "liqiang":91}中的值高於90的鍵值對編程
篩選集合{89, 70, 60, 80, 90}中能被3整除的元素app
通常遇到這種問題,咱們首先會想到用for循環的方式去解決dom
(1)for循環函數
from random import randint nums = [randint(-10, 10) for _ in range(20)] #生成一個列表 res_list = [] for ele in nums: if ele > 0: res_list.append(ele)
可是這種方式並不pythonicspa
(2)列表解析code
from random import randint nums = [randint(-10, 10) for _ in range(20)] res_list = [ele for ele in nums if ele > 0] #list comprehension
(3)filter函數htm
from random import randint nums = [randint(-10, 10) for _ in range(20)] res_filter = filter(lambda x: x > 0, nums) #filter res_list = list(res_filter)
(1)字典解析blog
from random import randint grade_info = {"stu%d" % i: randint(50, 100) for i in range(10)} res_dict = {k: v for k, v in grade_info.items() if v > 70}
(2)filter函數
from random import randint grade_info = {"stu%d" % i: randint(50, 100) for i in range(10)} res_filter = filter(lambda item: item[1] > 70, grade_info.items()) res_dict = dict(res_filter)
集合解析
from random import randint nums_set = {randint(10, 20) for _ in range(20)} nums_res = {ele for ele in nums_set if ele % 3 == 0}
filter函數
from random import randint nums_set = {randint(10, 20) for _ in range(10)} nums_filter = filter(lambda x: x % 3 == 0, nums_set) nums_res = set(nums_filter)
參考資料:python3實用編程技巧進階