本文實(shí)例講述了Python列表推導(dǎo)式、字典推導(dǎo)式與集合推導(dǎo)式用法。分享給大家供大家參考,具體如下:
推導(dǎo)式comprehensions(又稱解析式),是Python的一種獨(dú)有特性。推導(dǎo)式是可以從一個(gè)數(shù)據(jù)序列構(gòu)建另一個(gè)新的數(shù)據(jù)序列的結(jié)構(gòu)體。 共有三種推導(dǎo),在Python2和3中都有支持:
列表(list)推導(dǎo)式
字典(dict)推導(dǎo)式
集合(set)推導(dǎo)式
一、列表推導(dǎo)式
1、使用[]生成list
基本格式
variable = [out_exp_res for out_exp in input_list if out_exp == 2]
out_exp_res: 列表生成元素表達(dá)式,可以是有返回值的函數(shù)。
for out_exp in input_list: 迭代input_list將out_exp傳入out_exp_res表達(dá)式中。
if out_exp == 2: 根據(jù)條件過濾哪些值可以。
例一:
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*xmultiples = [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
將倆表推導(dǎo)式的[]改成()即可得到生成器。
multiples = (i for i in range(30) if i % 3 is 0)print(type(multiples))# Output: <type 'generator'>
二、字典推導(dǎo)式
字典推導(dǎo)和列表推導(dǎo)的使用方法是類似的,只不中括號(hào)該改成大括號(hào)。直接舉例說明:
例子一:大小寫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# Output: {'a': 17, 'b': 34}例子二:快速更換key和value
mcase = {'a': 10, 'b': 34}mcase_frequency = {v: k for k, v in mcase.items()}print mcase_frequency# Output: {10: 'a', 34: 'b'}三、集合推導(dǎo)式
它們跟列表推導(dǎo)式也是類似的。 唯一的區(qū)別在于它使用大括號(hào){}。
例一:
squared = {x**2 for x in [1, 1, 2]}print(squared)# Output: set([1, 4])更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python列表(list)操作技巧總結(jié)》、《Python數(shù)組操作技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python函數(shù)使用技巧總結(jié)》、《Python入門與進(jìn)階經(jīng)典教程》及《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選