编写一个生成器函数reverse_iter,该函数接受可迭代的序列并以相反的顺序生成项,而无需使用内置函数或方法。但是,使用该功能后,原始列表应保持不变。输出示例如下:
it = reverse_iter(nums)
next(it) == 4
True
next(it)
3
next(it)
2
next(it)
1
请注意,即使将列表更改为元组,以上内容也应起作用。我不知道如何不使用诸如reverse()或reversed()之类的方法。也许利用-1切片?有任何想法吗?
答案 0 :(得分:-2)
def reverse_iter(nums): # A generator function
idx = len(nums) - 1
while idx > -1:
yield nums[idx]
idx -=1
nums = [1,2,3,4]
print('before: ',*nums)
get = reverse_iter(nums) # get is a generator object
print('manually')
# Iterating over the generator object using next
print(get.__next__()) # In Python 3+ , print(get.__next__())
print(get.__next__())
print(get.__next__())
print(get.__next__())
#print(get.next()) #now you will get StopIteration
#print(next(get,'traversing complete')) #to avoid the StopIteration exception
# printing all items in list in reverse
print('\nusing for loop')
get = reverse_iter(nums) # get is a generator object
for i in range(len(nums)):
print(get.__next__())
print('after: ',*nums)