在reversed()上调用list()两次,第二次返回一个空列表

时间:2013-09-14 13:48:08

标签: python

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

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

1 个答案:

答案 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))