午夜国产狂喷潮在线观看|国产AⅤ精品一区二区久久|中文字幕AV中文字幕|国产看片高清在线

    Python的迭代器和生成器使用實(shí)例
    來源:易賢網(wǎng) 閱讀:1056 次 日期:2015-01-16 14:21:33
    溫馨提示:易賢網(wǎng)小編為您整理了“Python的迭代器和生成器使用實(shí)例”,方便廣大網(wǎng)友查閱!

    一、迭代器Iterators

    迭代器僅是一容器對象,它實(shí)現(xiàn)了迭代器協(xié)議。它有兩個基本方法:

    1)next方法

    返回容器的下一個元素

    2)__iter__方法

    返回迭代器自身

    迭代器可使用內(nèi)建的iter方法創(chuàng)建,見例子:

    代碼如下:

    >>> i = iter('abc')

    >>> i.next()

    'a'

    >>> i.next()

    'b'

    >>> i.next()

    'c'

    >>> i.next()

    Traceback (most recent call last):

    File "<string>", line 1, in <string>

    StopIteration:

    class MyIterator(object):

    def __init__(self, step):

    self.step = step

    def next(self):

    """Returns the next element."""

    if self.step==0:

    raise StopIteration

    self.step-=1

    return self.step

    def __iter__(self):

    """Returns the iterator itself."""

    return self

    for el in MyIterator(4):

    print el

    --------------------

    結(jié)果:

    代碼如下:

    3

    2

    1

    0

    二、生成器Generators

    從Python2.2起,生成器提供了一種簡潔的方式幫助返回列表元素的函數(shù)來完成簡單和有效的代碼。

    它基于yield指令,允許停止函數(shù)并立即返回結(jié)果。

    此函數(shù)保存其執(zhí)行上下文,如果需要,可立即繼續(xù)執(zhí)行。

    例如Fibonacci函數(shù):

    代碼如下:

    def fibonacci():

    a,b=0,1

    while True:

    yield b

    a,b = b, a+b

    fib=fibonacci()

    print fib.next()

    print fib.next()

    print fib.next()

    print [fib.next() for i in range(10)]

    --------------------

    結(jié)果:

    代碼如下:

    1

    1

    2

    [3, 5, 8, 13, 21, 34, 55, 89, 144, 233]

    PEP Python Enhancement Proposal Python增強(qiáng)建議

    tokenize模塊

    代碼如下:

    >>> import tokenize

    >>> reader = open('c:/temp/py1.py').next

    >>> tokens=tokenize.generate_tokens(reader)

    >>> tokens.next()

    (1, 'class', (1, 0), (1, 5), 'class MyIterator(object):/n')

    >>> tokens.next()

    (1, 'MyIterator', (1, 6), (1, 16), 'class MyIterator(object):/n')

    >>> tokens.next()

    (51, '(', (1, 16), (1, 17), 'class MyIterator(object):/n')

    例子:

    代碼如下:

    def power(values):

    for value in values:

    print 'powering %s' %value

    yield value

    def adder(values):

    for value in values:

    print 'adding to %s' %value

    if value%2==0:

    yield value+3

    else:

    yield value+2

    elements = [1,4,7,9,12,19]

    res = adder(power(elements))

    print res.next()

    print res.next()

    --------------------

    結(jié)果:

    代碼如下:

    powering 1

    adding to 1

    3

    powering 4

    adding to 4

    7

    保持代碼簡單,而不是數(shù)據(jù)。

    注意:寧可有大量簡單的可迭代函數(shù),也不要一個復(fù)雜的一次只計(jì)算出一個值的函數(shù)。

    例子:

    代碼如下:

    def psychologist():

    print 'Please tell me your problems'

    while True:

    answer = (yield)

    if answer is not None:

    if answer.endswith('?'):

    print ("Don't ask yourself too much questions")

    elif 'good' in answer:

    print "A that's good, go on"

    elif 'bad' in answer:

    print "Don't be so negative"

    free = psychologist()

    print free.next()

    print free.send('I feel bad')

    print free.send("Why I shouldn't ?")

    print free.send("ok then i should find what is good for me")

    --------------------

    結(jié)果:

    代碼如下:

    Please tell me your problems

    None

    Don't be so negative

    None

    Don't ask yourself too much questions

    None

    A that's good, go on

    None

    更多信息請查看IT技術(shù)專欄

    更多信息請查看腳本欄目
    易賢網(wǎng)手機(jī)網(wǎng)站地址:Python的迭代器和生成器使用實(shí)例
    由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

    2025國考·省考課程試聽報名

    • 報班類型
    • 姓名
    • 手機(jī)號
    • 驗(yàn)證碼
    關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機(jī)站點(diǎn) | 投訴建議
    工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
    云南網(wǎng)警備案專用圖標(biāo)
    聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
    咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
    云南網(wǎng)警報警專用圖標(biāo)