相关疑难解决方法(0)

Python的迭代器协议究竟是什么?

有客观的定义吗?它是作为python源代码的片段实现的吗?如果是这样,有人可以生成确切的代码行吗?是否所有语言都有自己的'for'语句迭代器协议?

python iteration

20
推荐指数
1
解决办法
7676
查看次数

使 Python 类支持 for 循环通过内部可迭代成员变量

from sortedcontainers import SortedSet

class BigSet(object):
    def __init__(self):
        self.set = SortedSet()
        self.current_idx = -1

    def __getitem__(self, index):
        try:
            return self.set[index]
        except IndexError as e:
            print('Exception: Index={0} len={1}'.format(index, len(self.ord_set)))
            raise StopIteration

    def add(self, element):
        self.set.add(element)

    def __len__(self):
        return len(self.set)

    def __iter__(self):
        self.current_idx = -1
        return self

    def __next__(self):
        self.current_idx += 1
        if self.current_idx == len(self.set):
            raise StopIteration
        else:
            return self.set[self.current_idx]

def main():
    big = BigSet()
    big.add(1)
    big.add(2)
    big.add(3)

    for b in big:
        print(b)

    for b2 in big:
        print(b2)

if __name__ == …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

2
推荐指数
1
解决办法
1279
查看次数

标签 统计

python ×2

iteration ×1

python-3.x ×1