Python内置函数reversed()用法分析

时间:2023-03-09 06:26:19
Python内置函数reversed()用法分析

Python内置函数reversed()用法分析

这篇文章主要介绍了Python内置函数reversed()用法,结合实例形式分析了reversed()函数的功能及针对序列元素相关操作技巧与使用注意事项,需要的朋友可以参考下

Python内置函数reversed()用法分析


reversed()函数是返回序列seq的反向访问的迭代器。参数可以是列表,元组,字符串,不改变原对象。



1》参数是列表  
 

>>>
l=[1,2,3,4,5]

>>>
ll=reversed(l)

>>> l

[1, 2, 3, 4, 5]

>>> ll



>>> for i in
ll:#第一次遍历

...  print i,

... 

5 4 3 2 1

>>> for i in
ll:第二次遍历为空,原因见本文最后

...  print i

...



2》参数是列表

>>> l=[3,4,5,6]

>>>
ll=reversed(l)

>>> l

[3, 4, 5, 6]

>>> ll



>>> list(ll)#第一次

[6, 5, 4, 3]

>>>
list(ll)#第二次为空,原因见本文最后

[]



3》参数是元组  
 

>>> t=(4,5,6)

>>>
tt=reversed(t)

>>> t

(4, 5, 6)

>>> tt



>>>
tuple(tt)#第一次

(6, 5, 4)

>>>
tuple(tt)#第二次为空,原因见本文最后

()



4》参数是字符串  
 

>>> s='cba'

>>>
ss=reversed(s)

>>> s

'cba'

>>> ss



>>> list(ss)#第一次

['a', 'b', 'c']

>>>
list(ss)#第二次为空,原因见本文最后

[]



5》参数是字符串  
 

>>> 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()之后,只在第一次遍历时返回值。