【问题标题】:Not able to write a iterator for a Linked List created in python [duplicate]无法为在 python 中创建的链表编写迭代器 [重复]
【发布时间】:2014-06-29 09:21:20
【问题描述】:

已尝试创建 python 单链表,但我无法创建迭代器。 这是我的代码:

class LinkedList:
    def __init__(self):
        self._head=self
        self._tail=self
        self._size=0                    

    def __iter__(self):
        print 'Calling Iterator\n\n'
        _ListIterator(self._head)

class ListObj:
    def __init__(self,value):
        self._data=value
        self._pointingTo=None

class _ListIterator:
    def __init__(self,listHead):
        LIST=None
        self._curNode=listHead
        print dir(self._curNode)

    def __next__(self):
        if self._curNode._pointingTo is None:
            raise StopIteration
        else:
            item=self._curNode._data
            self._curNode=self._curNode._pointingTo
            return item

这个迭代器因为抛出一个错误而失败

TypeError: __iter__ returned non-iterator of type 'NoneType'

【问题讨论】:

  • 你真的要发布整个代码吗?请阅读sscce.org另外,请显示您的整个回溯。
  • 好的,我知道我在迭代器中只传递了一个 LinkedList 对象,但是我怎样才能将完整的列表作为一个整体传递!
  • 这是整个回溯:回溯(最近一次调用最后一次):文件“”,第 1 行,在 类型错误:iter 返回非迭代器类型为“NoneType”
  • 没有理由创建ListIterator 对象。阅读重复的问题并尝试。
  • 是的,链接有帮助,让它成为一个单独的对象是没有意义的!谢谢乐高冲锋队

标签: python singly-linked-list


【解决方案1】:
_ListIterator(self._head)

你忘了return这个。

【讨论】:

  • 谢谢,得到了让它在有/没有单独的迭代器对象的情况下工作的所有可能性:)
猜你喜欢
  • 2015-02-20
  • 2020-08-05
  • 2018-04-26
  • 1970-01-01
  • 2020-08-14
  • 2018-10-06
  • 2020-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多