第二次使用迭代器时"reversed"空列表



为什么第二个打印命令给出一个空列表,而第一个打印命令给出正确的输出?

str1 = 'Hello'
str2 = reversed(str1)
print(list(str2))
print(list(str2))

输出:

['o', 'l', 'l', 'e', 'H']
[]

反转是一个迭代器,迭代器只能被消费一次,这意味着一旦你对它们进行迭代,你就不能再重复了。

检查文档

[](空list)原因

内置的reversed是一个迭代器,因此一旦消耗了,它就会通过生成list耗尽。在你的情况下,一旦你做了,list(revered("Hello")),它变成,耗尽

解决方案一个快速的解决方案是创建另一个迭代器,code:
str1 = "Hello" # Original String 
iter1 = reversed(str1) # Making the first iterator 
iter2 = reversed(str1) # Making the second iterator 
print(list(iter1), list(iter2)) # Printing the iterator once they are lists

最新更新