python:为什么reversed()之后,第二次以后的list()得到的结果都是空?

在测试list()与reversed()结合时,碰到如下结果:

>>> a = '123 456'
>>> b = reversed(list(a.split()))
>>> b
<list_reverseiterator object at 0x0000000002D45FD0>
>>> list(b)
['456', '123']
>>> list(b)
[]
>>> list(b)
[]
>>> list(b)
[]
>>>

为什么reversed()之后,第二次及以后的list()得到的list都是空?google得到的解答如下:

解释一:
That’s because reversed creates an iterator, which is already spent when you’re calling list(bb) for the second time.

解释二:
The reason is that b is not the reversed list itself, but a listreverseiterator. So when you call list() the first time, it iterates over b and creates a new list from the items output from that iterator. When you do it a second time, b is still the original iterator and has already gone through all the items, so it doesn’t iterate over anything, resulting in an empty list



python自带文档对于reversed()的描述如下:

这里写图片描述
reversed(seq)
Return a reverse iterator. seq must be an object which has a reversed() method or supports the sequence protocol (the len() method and the getitem() method with integer arguments starting at 0).


这里写图片描述
object.reversed(self)
Called (if present) by the reversed() built-in to implement reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order.

If the reversed() method is not provided, the reversed() built-in will fall back to using the sequence protocol (len() and getitem()). Objects that support the sequence protocol should only provide reversed() if they can provide an implementation that is more efficient than the one provided by reversed().

reversed()之后的iterator只在第一次遍历时返回值。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值