为什么第二个打印命令给出一个空列表,而第一个打印命令给出正确的输出?
str1 = 'Hello'
str2 = reversed(str1)
print(list(str2))
print(list(str2))
输出:
['o', 'l', 'l', 'e', 'H']
[]
反转是一个迭代器,迭代器只能被消费一次,这意味着一旦你对它们进行迭代,你就不能再重复了。
检查文档
[]
(空list
)原因
内置的reversed
是一个迭代器,因此一旦消耗了,它就会通过生成list
耗尽。在你的情况下,一旦你做了,list(revered("Hello"))
,它变成,耗尽。
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