栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/444227.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号