本文實例講述了python迭代器的簡單用法,分享給大家供大家參考。具體分析如下:
生成器表達式是用來生成函數調用時序列參數的一種迭代器寫法
生成器對象可以遍歷或轉化為列表(或元組等數據結構),但不能切片(slicing)。當函數的唯一的實參是可迭代序列時,便可以去掉生成器表達式兩端>的圓括號,寫出更優雅的代碼:
>>>> 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().
參數要求傳入可迭代序列,我們傳入一個生成器對象,完美實現。
注意區分下面代碼:
上面的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)
結果:
at 0x01CB1A30> ********************************************************************** [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
希望本文所述對大家Python程序設計的學習有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
