Python 推導式(列表推導式,字典推導式,集合推導式)
阿新 • • 發佈:2019-04-06
ron 生成 轉載 一個 inpu frequency 括號 結果 lower
Python的各種推導式
推導式comprehensions(又稱解析式),是Python的一種獨有特性。推導式是可以從一個數據序列構建另一個新的數據序列的結構體。 共有三種推導。
列表推導式
字典推導式
集合推導式
列表推導式
1.使用[]生成list
var = [out_exp_put for out_exp in input_list if out_exp == 2] out_exp_put 列表生成出來的表達式,可以是有返回值的函數。 for out_exp in input_list 叠代input_list將out_exp傳入out_exp_put中。 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]
2.使用()生成generator
將列表推導式的[]改成()即可得到生成器。
multiples = (i for i in range(30) if i % 3 is 0)
print(type(multiples))
#結果
<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 #結果 {'a': 17, 'b': 34}
例子二:
mcase = {'a':10,'b':34}
mcase_frequency = {v:k for k,v in mcase.items()}
print mcase_frequency
#結果
{10:'a',34:'b'}
集合推導式
跟列表推導式類似,區別在於使用的是大括號{}
squared = {x**2 for x in [1, 1, 2]}
print(squared)
#結果
set([1, 4])
轉載自:https://www.cnblogs.com/tkqasn/p/5977653.html
Python 推導式(列表推導式,字典推導式,集合推導式)