反向函数返回的 'iterator object' 是什么?

What is an 'iterator object' as returned by the reversed function?

我正在尝试在列表中使用 reversed 函数,但我遇到了 return 值的问题。

s=[0,1,2,3]
print(reversed(s))

这 return 这行: <list_reverseiterator object at 0x000001488B6559A0>

我知道 reversed() 函数 return 是一个迭代器对象。有人可以详细说明 'iterator object' 吗?

迭代器对象实际上与生成器是一回事。

来自docs

Generators are iterators, but you can only iterate over them once. It’s because they do not store all the values in memory, they generate the values on the fly. You use them by iterating over them, either with a ‘for’ loop or by passing them to any function or construct that iterates. Most of the time generators are implemented as functions. However, they do not return a value, they yield it.

解决这个问题的方法是:

print(list(reversed(s)))

输出:

[3, 2, 1, 0]

你知道,通过使用这个反向函数,你将以相反的顺序迭代列表。这样做

s=[0,1,2,3]
reversed_s = reversed(s)
for item in reversed_s:
    print(item)