2

我不明白这段代码的结果:

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 []

4

1 回答 1

8

那是因为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))

于 2013-09-14T13:50:02.743 回答