写一个反向迭代器python

我正在尝试不使用反向功能编写自己的反向迭代器。我的问题是怎么做?此代码不起作用。


def my_iter(iterable):

    temp = []

    for i in range(len(iterable) - 1, -1, -1):

        #print(i)

        j = 0

        temp[i] = iterable[i]

        j += 1

    return temp

例如:my_list = [78, 120, 3] my_iter(my_list) 输出:3, 120, 78


撒科打诨
浏览 150回答 2
2回答

哈士奇WWW

您还可以使用双指针方法来反转列表。def my_iter(iterable):&nbsp; &nbsp; i = 0&nbsp; &nbsp; j = len(iterable)-1&nbsp; &nbsp; while i <= j:&nbsp; &nbsp; &nbsp; &nbsp; temp = iterable[i]&nbsp; &nbsp; &nbsp; &nbsp; iterable[i] = iterable[j]&nbsp; &nbsp; &nbsp; &nbsp; iterable[j] = temp&nbsp; &nbsp; &nbsp; &nbsp; i+=1&nbsp; &nbsp; &nbsp; &nbsp; j-=1&nbsp; &nbsp; return iterableprint(my_iter([78, 120, 3]))#[3, 120, 78]

四季花海

当您可以直接迭代时,不需要自定义反向迭代器iterable[::-1]。使用yieldin loop,你可以收获 generator 的优势:def my_iter(iterable):&nbsp; &nbsp; for x in iterable[::-1]:&nbsp; &nbsp; &nbsp; &nbsp; yield xmy_list = [78, 120, 3]rev_iter = my_iter(my_list)print(next(rev_iter))&nbsp; # 3print(next(rev_iter))&nbsp; # 120print(next(rev_iter))&nbsp; # 78# calling next() again throws a StopIteration.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python