新聞中心
1、推導(dǎo)式的方法,只需將列表生成的[]改為()

成都創(chuàng)新互聯(lián)公司專注于長(zhǎng)興網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供長(zhǎng)興營(yíng)銷型網(wǎng)站建設(shè),長(zhǎng)興網(wǎng)站制作、長(zhǎng)興網(wǎng)頁設(shè)計(jì)、長(zhǎng)興網(wǎng)站官網(wǎng)定制、小程序制作服務(wù),打造長(zhǎng)興網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供長(zhǎng)興網(wǎng)站排名全網(wǎng)營(yíng)銷落地服務(wù)。
創(chuàng)建生成器的方法有很多。
In [26]: L = [num * 2 for num in range(5)] In [27]: L Out[27]: [0, 2, 4, 6, 8] In [28]: G = (num * 2 for num in range(5)) In [29]: G Out[29]:at 0x000001D62EA28248>
2、next() 函數(shù)
In [30]: next(G) Out[30]: 0 In [31]: next(G) Out[31]: 2 In [32]: next(G) Out[32]: 4 In [33]: next(G) Out[33]: 6 In [34]: next(G) Out[34]: 8 In [35]: next(G) --------------------------------------------------------------------------- StopIteration Traceback (most recent call last)in ----> 1 next(G) StopIteration:
3、for循環(huán)與list,因?yàn)镚已經(jīng)迭代到了ipython測(cè)試的最后,所以需要重建G,否則就沒有數(shù)據(jù)了。
In [38]: G = (num * 2 for num in range(5)) In [39]: for i in G: ...: print(i) ...: 0 2 4 6 8 In [40]: list(G) Out[40]: [] In [41]: G = (num * 2 for num in range(5)) In [42]: list(G) Out[42]: [0, 2, 4, 6, 8]
以上就是python生成器創(chuàng)建的方法整理,希望對(duì)大家有所幫助。更多編程基礎(chǔ)知識(shí)學(xué)習(xí):python學(xué)習(xí)網(wǎng)
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
當(dāng)前標(biāo)題:創(chuàng)新互聯(lián)Python教程:python生成器創(chuàng)建的方法整理
網(wǎng)頁鏈接:http://fisionsoft.com.cn/article/dhdeoje.html


咨詢
建站咨詢
