我有list个自定义类对象(示例如下).

使用:list(itertools.chain.from_iterable(myBigList))我想把stations个子列表"合并"成一个大列表.所以我想我需要让我的定制类变得更容易使用.

这是我的自定义类的一个示例.

class direction(object) :
    def __init__(self, id) :
        self.id = id              
        self.__stations = list()

    def __iter__(self):
        self.__i = 0                #  iterable current item 
        return iter(self.__stations)

    def __next__(self):
        if self.__i<len(self.__stations)-1:
            self.__i += 1         
            return self.__stations[self.__i]
        else:
            raise StopIteration

我实现了__iter____next__,但似乎不起作用.他们连电话都没打.

知道我做错了什么吗?

注意:使用Python 3.3

推荐答案

__iter__是在try 迭代类实例时调用的值:

>>> class Foo(object):
...     def __iter__(self):
...         return (x for x in range(4))
...
>>> list(Foo())
[0, 1, 2, 3]

__next__是从__iter__返回的对象上被调用的值(在python2.x上,它是next,而不是__next__——我通常将它们都命名为别名,以便代码可以使用其中一个…:

class Bar(object):
    def __init__(self):
        self.idx = 0
        self.data = range(4)
    def __iter__(self):
        return self
    def __next__(self):
        self.idx += 1
        try:
            return self.data[self.idx-1]
        except IndexError:
            self.idx = 0
            raise StopIteration  # Done iterating.
    next = __next__  # python2.x compatibility.

在 comments 中,有人问你如何构造可以多次迭代的对象.在这种情况下,我建议采用与Python相同的方法,从数据容器中拆分迭代器:

class BarIterator(object):
    def __init__(self, data_sequence):
        self.idx = 0
        self.data = data_sequence
    def __iter__(self):
        return self
    def __next__(self):
        self.idx += 1
        try:
            return self.data[self.idx-1]
        except IndexError:
            self.idx = 0
            raise StopIteration  # Done iterating.


class Bar(object):
    def __init__(self, data_sequence):
        self.data_sequence = data_sequence
    def __iter__(self):
        return BarIterator(self.data_sequence)

Python-3.x相关问答推荐

Numba编译时间呈指数级增长--可以像C编译器一样配置优化级别吗?

数据类对象列表的字典获取方法-在数据类列表中查找具有特定变量值的数据类

数据框中从每个组/ID的底部删除行

在一行中读写一个csv文件

使用 multiprocessing 处理图像

使用gekko python的混合整数非线性规划

如何在 Telethon 中向机器人发送发送表情符号

python2和python3中的列表生成器

这种类型提示有什么作用?

使用正确的数据类型时,使用 Cerberus 验证 JSON 架构会引发错误

在不使用字符串方法的情况下查找字符串最后一个单词的长度 - Python

为什么我不能通过索引获取字典键?

在python中循环处理时并行写入文件

Tkinter AttributeError:对象没有属性'tk'

Pylint 给我最后的新行丢失

IronPython 3 支持?

用 numpy nan 查找列表的最大值

使用 asyncio 的多个循环

如何在 QGraphicsView 中启用平移和zoom

如何使用 python http.server 运行 CGI hello world