Heim  >  Fragen und Antworten  >  Hauptteil

Call a function until a sentinel value 代码解读?

blocks=[]
while True:
    block=f.read(32)
    if block=='':
        break
    blocks.append(block)

改写:    
blocks=[]
for block in iter(partial(f.read,32),''):
    blocks.append(block)


高洛峰高洛峰2913 Tage vor811

Antworte allen(1)Ich werde antworten

  • 三叔

    三叔2016-10-27 09:35:08

    手机码字。

    这段代码巧妙利用了 iter 的另一种形式:

    1.jpg

    如果传给 iter 的是两个参数: callable 和 sentinel,则返回的生成器会反复调用 callable 并 yield 其返回值,直到返回值和 sentinel 相等时停止。

    等价代码:

    def iter(callable, sentinel):
        while True:
            val = callable()
            if val == sentinel: break
            yield val


    Antwort
    0
  • StornierenAntwort