python中reversed用法_Python内置函数reversed()用法分析

>>> s='1234'

>>>

ss=reversed(s)

>>> s

'1234'

>>> ss

>>>

''.join(ss)#第一次

'4321'

>>>

''.join(ss)#第二次为空,原因见本文最后

''

为什么reversed()之后,第二次for循环或第二次list()或第二次tuple()或第二次join()得到的结果为空?我们以第2个例子具体说明一下:

That's because reversed creates an iterator, which is already spent

when you're calling list(ll) for the second time.

The reason is that ll is not the reversed list itself, but a

listreverseiterator. So when you call list(ll) the first time, it

iterates over ll and creates a new list from the items output from

that iterator.When you do it a second time, ll 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.

小编来翻译一下:

这是因为反向创建了一个迭代器,该迭代器在第二次调用列表(LL)时已经使用过了。

其原因就是ll不是反转列表本身,而是一个列表反向迭代器。所以当你第一次调用列表(ll),它会遍历ll并且创建一个新的列表从项目输出迭代器。当你再进行一次,ll仍然是原来的迭代器,已经经历了所有的项目,所以它不会再遍历什么,这就造成了空列表。

总结:reversed()之后,只在第一次遍历时返回值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值