python - 链表遍历输出的3种方法

使用yield & list()

    def items(self):
        current=self.head
        while current !=None:
            yield current.data
            current=current.getNext()


    for i in range(5):
        myList.add(i)
    print(list(myList.items()))  # [4, 3, 2, 1, 0]

链表可迭代化

参考1:Python.__getitem__方法_嘟嘟嘟嘟-CSDN博客_getitem

参考2:python之__iter__函数与__next__函数_Webbley的博客-CSDN博客

1. 使用__getitem__()

在用 for..in.. 迭代对象时,如果对象没有实现 __iter__ __next__ 迭代器协议,Python的解释器就会去寻找__getitem__ 来迭代对象,如果连__getitem__ 都没有定义,这解释器就会报对象不是迭代器的错误。而实现这个方法后,就可以正常迭代对象了。

思路:在getitem中转换成一个可迭代的对象,eg list[],然后用list来迭代。

感觉,如果数据很多的话,空间性能不太好,不如yield呢。

object.__getitem__(selfkey)

Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects.

    def __getitem__(self,key):
        if isinstance(key,int): # 判断key是不是整数
            if 0<=key<=self.length(): # 判断key的范围
                # 循环找key,生成列表,返回list[key]
                current=self.head
                list=[]
                while current!=None:
                    list.append(current.getData())
                    current=current.getNext()
                return list[key]
            else:
                raise IndexError("indexError")
        else:
            raise Exception("please input a int key")



if __name__=="__main__":
    for i in range(myList.length()):
        print(myList[i])

2. 使用__iter__()、__next__()

for … in… 这个语句其实做了两件事。第一件事是获得一个可迭代器,即调用了__iter__()函数。
第二件事是循环的过程,循环调用__next__()函数。

只要有__next__(),就可以迭代了。(__iter__()感觉是默认有的耶)

iterator.__iter__()

Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. 

iterator.__next__()

Return the next item from the container. If there are no further items, raise the StopIteration exception. 

简单讲地是:python里的iteratior机制。

Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.

Once an iterator’s __next__() method raises StopIteration, it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.

用一下别人的部分代码吧,这里我没写出来,呜呜呜。学习!


    # 可迭代条件
    def __iter__(self):
        return self
 
    # 迭代器条件
    def __next__(self):
        if self.current is not None:
            temp = self.current
            self.current = self.current.next
            return temp
        else:
            # 如果current到了表尾,则将current重新指向表头
            self.current = self.head

————————————————
版权声明:本文为CSDN博主「五力」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lxy210781/article/details/87125093

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值