python迭代器實例簡析
本文實例講述了python迭代器的簡單用法,分享給大家供大家參考。具體分析如下:
生成器表達式是用來生成函數(shù)調(diào)用時序列參數(shù)的一種迭代器寫法
生成器對象可以遍歷或轉(zhuǎn)化為列表(或元組等數(shù)據(jù)結(jié)構(gòu)),但不能切片(slicing)。當函數(shù)的唯一的實參是可迭代序列時,便可以去掉生成器表達式兩端>的圓括號,寫出更優(yōu)雅的代碼:
>>>> sum(i for i in xrange(10)) 45
sum聲明:
sum(iterable[, start])
Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate a sequence of strings is by calling ''.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) To add floating point values with extended precision, see math.fsum().
參數(shù)要求傳入可迭代序列,我們傳入一個生成器對象,完美實現(xiàn)。
注意區(qū)分下面代碼:
上面的j為生成器類型,下面的j為list類型:
j = (i for i in range(10)) print j,type(j) print '*'*70 j = [i for i in range(10)] print j,type(j)
結(jié)果:
<generator object <genexpr> at 0x01CB1A30> <type 'generator'> ********************************************************************** [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <type 'list'>
希望本文所述對大家Python程序設(shè)計的學習有所幫助。
相關(guān)文章
python使用pywinauto驅(qū)動微信客戶端實現(xiàn)公眾號爬蟲
這個項目是通過pywinauto控制windows(win10)上的微信PC客戶端來實現(xiàn)公眾號文章的抓取。代碼分成server和client兩部分。server接收client抓取的微信公眾號文章,并且保存到數(shù)據(jù)庫。另外server支持簡單的搜索和導出功能。client通過pywinauto實現(xiàn)微信公眾號文章的抓取。2021-05-05python爬取網(wǎng)頁內(nèi)容轉(zhuǎn)換為PDF文件
這篇文章主要為大家詳細介紹了python爬取網(wǎng)頁內(nèi)容轉(zhuǎn)換為PDF文件,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06Django celery實現(xiàn)異步任務(wù)操作,并在后臺運行(守護進程)
這篇文章主要介紹了Django celery實現(xiàn)異步任務(wù)操作,并在后臺運行(守護進程),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03