• 列表推导式
1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 # 列表推导式性能高于列表操作 4 5 odd_list = [] 6 for i in range(21): 7 if i%2 == 1: 8 odd_list.append(i) 9 10 # 提取1-20之间的奇数 11 odd_list = [i for i in range(21) if i % 2 == 1] 12 print(odd_list) 13 14 # 提取1-20之间的奇数,并且平方 15 16 17 def pow_item(item): 18 return item*item 19 20 21 odd_list = [pow_item(i) for i in range(21) if i % 2 == 1] 22 print(odd_list)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19] [1, 9, 25, 49, 81, 121, 169, 225, 289, 361]
• 生成器表达式
1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 # 生成器表达式 4 5 odd_gen = (i for i in range(21) if i % 2 == 1) 6 print(type(odd_gen)) 7 print(odd_gen) 8 9 for item in odd_gen: 10 print(item) 11 12 odd_list = list(odd_gen) 13 print(type(odd_list)) 14 print(odd_list)
<class 'generator'> <generator object <genexpr> at 0x0000015819C82660> 1 3 5 7 9 11 13 15 17 19
• 字典推导式
1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 # 字典推导式 4 my_dict = {'zy1': 11, 'zy2': 22, 'zy3': 33} 5 reversed_dict = {value: key for key, value in my_dict.items()} 6 print(reversed_dict) 7 8 # 集合推导式 9 my_set = {key for key, value in my_dict.items()} 10 print(type(my_set)) 11 print(my_set)
{11: 'zy1', 22: 'zy2', 33: 'zy3'} <class 'set'> {'zy3', 'zy2', 'zy1'}