# 『Python基礎-12』各種推導式(列表推導式、字典推導式、集合推導式)
推導式comprehensions(又稱解析式),是Python的一種獨有特性。推導式是可以從一個數據序列構建另一個新的數據序列的結構體。 共有三種推導,在Python2和3中都有支持:
目錄:
- 列表(list)推導式
- 字典(dict)推導式
- 集合(set)推導式
1.列表推導式
1.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)
運行結果: [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
運行結果: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
1.2、 使用()生成generator
將倆表推導式的[]改成()即可得到生成器:
multiples = (i for i in range(30) if i % 3 is 0)
print(type(multiples))
運行結果:<type 'generator'>
2. 字典推導式
字典推導和列表推導的使用方法是類似的,只不中括號該改成大括號。
示例一: 大小寫key合并:
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
運行結果:{'a': 17, 'b': 34}
示例二: 快速更換key和value:
mcase = {'a': 10, 'b': 34}
mcase_frequency = {v: k for k, v in mcase.items()}
print mcase_frequency
運行結果:{10: 'a', 34: 'b'}
3. 集合推導式
它們跟列表推導式也是類似的。 唯一的區別在于它使用大括號{}。
squared = {x**2 for x in [1, 1, 2]}
print(squared)
運行結果: Output: set([1, 4])
這篇筆記來自: cnblog