>>> x = "hello world"
>>> y = reversed(x)
>>> z = ''.join(y)
>>> z
'dlrow olleh'
>>> y
<reversed object at 0x7f2871248b38>
>>> ''.join(y)
''
>>> x
'hello world'
>>> ''.join(y)
''
>>> z = ''.join(y)
>>> z
''
为什么在反向函数中执行联接操作后,下次将z的值作为空白字符串获取
答案 0 :(得分:2)
这是因为reversed返回一个迭代器,当您对其应用操作时,它将“消耗”该元素。如果要将反转结果存储在变量中,联接是一种很好的方法。
from collections.abc import Iterator
print(isinstance(reversed("hello world"), Iterator)) # True
it = reversed("hello world")
for x in it:
print(x) # Prints the letters
for x in it:
print(x) # Do not print them, there are already "consumed"