久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何讓生成器/迭代器在用盡時評估為 False?

How can I get generators/iterators to evaluate as False when exhausted?(如何讓生成器/迭代器在用盡時評估為 False?)
本文介紹了如何讓生成器/迭代器在用盡時評估為 False?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

Python 中的其他空對象評估為 False —— 我怎樣才能讓迭代器/生成器也這樣做?

Other empty objects in Python evaluate as False -- how can I get iterators/generators to do so as well?

推薦答案

默認(rèn)情況下,Python 中的所有對象都評估為 True.為了支持 False 評估,對象的類必須具有 __len__ 方法(0 -> False),或 __nonzero__ 方法 (False -> False).注意:__nonzero__ ==> __bool__ 在 Python 3.x 中.

By default all objects in Python evaluate as True. In order to support False evaluations the object's class must have either a __len__ method (0 -> False), or a __nonzero__ method (False -> False). Note: __nonzero__ ==> __bool__ in Python 3.x.

因為迭代器協(xié)議有意保持簡單,并且因為有許多類型的迭代器/生成器在嘗試生成它們之前無法知道是否還有更多值要生成,所以 True/False 評估不是迭代器協(xié)議的一部分.

Because the iterator protocol is intentionally kept simple, and because there are many types of iterators/generators that aren't able to know if there are more values to produce before attempting to produce them, True/False evaluation is not part of the iterator protocol.

如果你真的想要這種行為,你必須自己提供.一種方法是將生成器/迭代器包裝在提供缺失功能的類中.

If you really want this behavior, you have to provide it yourself. One way is to wrap the generator/iterator in a class that provides the missing functionality.

請注意,此代碼僅在引發(fā) StopIteration 后評估為 False .

Note that this code only evaluates to False after StopIteration has been raised.

作為獎勵,此代碼適用于 pythons 2.4+

As a bonus, this code works for pythons 2.4+

try:
    next
except NameError:       # doesn't show up until python 2.6
    def next(iter):
        return iter.next()

Empty = object()

class Boolean_Iterator(object):
    """Adds the abilities
    True/False tests:  True means there /may/ be items still remaining to be used
    """
    def __init__(self, iterator):
        self._iter = iter(iterator)
        self._alive = True
    def __iter__(self):
        return self
    def __next__(self):
        try:
            result = next(self._iter)
        except StopIteration:
            self._alive = False
            raise
        return result
    next = __next__                     # python 2.x
    def __bool__(self):
        return self._alive
    __nonzero__ = __bool__              # python 2.x

如果您還想要前瞻(或窺視)行為,則此代碼可以解決問題(它的計算結(jié)果為 False before StopIteration被提出):

If you also want look-ahead (or peek) behavior, this code will do the trick (it evaluates to False before StopIteration is raised):

try:
    next
except NameError:       # doesn't show up until python 2.6
    def next(iter):
        return iter.next()

Empty = object()

class Iterator(object):
    """Adds the abilities
    True/False tests:  True means there are items still remaining to be used
    peek(): get the next item without removing it from the sequence
    """
    def __init__(self, iterator):
        self._iter = iter(iterator)
        self._peek = Empty
        self.peek()
    def __next__(self):
        peek, self._peek = self._peek, Empty
        self.peek()
        if peek is not Empty:
            return peek
        raise StopIteration
    next = __next__                     # python 2.x
    def __bool__(self):
        return self._peek is not Empty
    __nonzero__ = __bool__              # python 2.x
    def peek(self):
        if self._peek is not Empty:
            return self._peek
        self._peek = next(self._iter, Empty)
        return self._peek

請記住,當(dāng)?shù)讓拥?生成器的時間與其產(chǎn)生的值相關(guān)時,窺視行為是不合適的.

Keep in mind that peek behaviour is not appropriate when the timing of the underlying iterator/generator is relevant to its produced values.

另外請記住,第三方代碼,可能還有標(biāo)準(zhǔn)庫,可能依賴于迭代器/生成器,總是評估為 True.如果你想在沒有 bool 的情況下查看,請刪除 __nonzero____bool__ 方法.

Also keep in mind that third-party code, and possibly the stdlib, may rely on iterators/generators always evaluating to True. If you want peek without bool, remove the __nonzero__ and __bool__ methods.

這篇關(guān)于如何讓生成器/迭代器在用盡時評估為 False?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區(qū)域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應(yīng)用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據(jù)文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 亚洲性人人天天夜夜摸 | 欧美 日本 国产 | 日韩一区二区福利视频 | 久久久久久亚洲精品不卡 | 日韩欧美三级电影在线观看 | 欧美日韩专区 | 国产日韩免费视频 | 成人欧美一区二区三区视频xxx | 99热精品久久 | 久久久久无码国产精品一区 | 精品久久久久久亚洲综合网 | 青青草网 | 看亚洲a级一级毛片 | 99热首页| 激情五月婷婷 | 一级片av| 91精品中文字幕一区二区三区 | www国产成人免费观看视频,深夜成人网 | 超级黄色一级片 | 成年女人免费v片 | 欧美激情久久久 | 美女国产一区 | 少妇一级淫片aaaaaaaaa | 青青久久av北条麻妃海外网 | 亚洲欧美在线一区 | 69xxx免费| 99re66在线观看精品热 | 国产精品久久国产精品99 gif | 欧美另类日韩 | 国产成人精品久久二区二区 | 国产精品一区二区三区久久 | 国产精品一区二区视频 | 色久伊人| 日韩2020狼一二三 | 国产视频福利在线观看 | 成人av免费播放 | 操夜夜 | 国产 日韩 欧美 在线 | 欧美综合视频在线 | 国产电影一区 | 久久精品|