我不明白这段代码的结果:
aa = 'hello, world'
bb = reversed(aa)
print(bb)
print(list(bb))
print(bb)
dd = list(bb)
print(dd)
print(''.join(dd))
结果:
<reversed object at 0x025C8C90>
['d', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'h']
<reversed object at 0x025C8C90>
[]
为什么dd
[]
?
答案 0 :(得分:7)
那是因为reversed
创建了一个迭代器,当你第二次调用list(bb)
时就已经花了它。
aa = 'hello, world'
bb = reversed(aa) # Creates an iterator, not a list
print(bb) # Prints "<reversed object at 0x10c619b90>" (that's the iterator)
print(list(bb)) # Pops items from the iterator to create a list, then prints the list
print(bb) # At this point the iterator is spent, and doesn't contain elements anymore
dd = list(bb) # Empty iterator -> Empty list ([])
print(dd)
print(''.join(dd))
print('----------')
要解决此问题,只需按reversed(aa)
更改list(reversed(aa))
。