python 字典、列表、元組產生器的使用

來源:互聯網
上載者:User

標籤:print   取數   代碼   pass   操作   類型   generator   else   obj   

python的產生式在一些類型相互轉換的時候可以寫出十分優雅的代碼。如列錶轉換成另一個列表、字典、或元組。並且代碼的執行效率也比使用for...in...迴圈高。

列表產生式

列表產生式即產生列表的產生式,寫法簡單而優雅,可以將多行代碼融合成一行。主要的作用是將其他對象轉換成列表或對原來的列表進行過濾。

# 列錶轉換列表ls = [1,2,4,6]ls1 = [x**2 for x in ls]print(ls1)結果:[1,4,16,36]# 對列表過濾,返回true的才會保留到列表ls = [1,2,4,6]ls1 = [x**2 for x in ls if x > 3]print(ls1)結果:[16, 36]# 多條件過濾ls = [1,2,4,6]ls1 = [x**2 if x > 2 else x**3 for x in ls]print(ls1)結果:[1, 8, 16, 36]# 多重迴圈ls = [1,2,4,6]ls1 = [x**y if x > 2 else x**3 for x in ls for y in ls]print(ls1)結果:[1, 1, 1, 1, 8, 8, 8, 8, 4, 16, 256, 4096, 6, 36, 1296, 46656]

 

產生器產生式
  • 在涉及到需要遍曆列表而不是針對列表的某個值操作時,使用產生器代替列表可以減少記憶體的消耗。
ls = [1,2,4,6]ls1 = (x**2 for x in ls)print(ls1)結果:<generator object <genexpr> at 0x0000021B21DED150># 通過for..in取資料不需要處理StopIterationfor i in ls1:    pass# next()方法需要處理StopIterationwhile True:    try:        print(next(ls1))    except StopIteration:        pass

 

字典產生式

字典產生式在一些需要列表或元組轉化成字典的場合可以寫出很優雅的代碼。

# dict()可以接受類似列表產生式的寫法,前提是ls至少是二維可迭代對象,否則報錯ls = [(‘name1‘,‘xiao‘),(‘name2‘,‘wang‘)]dict_ls = dict(x for x in ls)print(dict_ls)結果:{‘name1‘: ‘xiao‘, ‘name2‘: ‘wang‘}

 

元組產生式

由於()這個類似列表產生式的形式被產生器佔用了,所有元組產生式使用tuple()來進行。

ls = [(‘name1‘,[‘1‘,‘2‘]),(‘name2‘,‘wang‘)]dict_ls = tuple(x for x in ls)print(dict_ls)結果:((‘name1‘, [‘1‘, ‘2‘]), (‘name2‘, ‘wang‘))

 

 

python 字典、列表、元組產生器的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.