# Python列表推導式、字典推導式與集合推導式用法例項分析

1、使用[]生成list

variable = [out_exp_res for out_exp in input_list if out_exp == 2]

out_exp_res:　　列表生成元素表示式，可以是有返回值的函式。
for out_exp in input_list：　　迭代input_list將out_exp傳入out_exp_res表示式中。
if out_exp == 2：　　根據條件過濾哪些值可以。

``````
multiples = [i for i in range(30) if i % 3 is 0]
print(multiples)
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
``````

``````
def squared(x):
return x*x
multiples = [squared(i) for i in range(30) if i % 3 is 0]
print multiples
# Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
``````

2、使用()生成generator

``````
multiples = (i for i in range(30) if i % 3 is 0)
print(type(multiples))
# Output: <type 'generator'>
``````

``````
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
mcase_frequency = {
k.lower(): mcase.get(k.lower(), 0)   mcase.get(k.upper(), 0)
for k in mcase.keys()
if k.lower() in ['a','b']
}
print mcase_frequency
# Output: {'a': 17, 'b': 34}
``````

``````
mcase = {'a': 10, 'b': 34}
mcase_frequency = {v: k for k, v in mcase.items()}
print mcase_frequency
# Output: {10: 'a', 34: 'b'}
``````

``````
squared = {x**2 for x in [1, 1, 2]}
print(squared)
# Output: set([1, 4])
``````