python 内置函数 reversed()
来源:互联网 发布:招商银行 知乎 编辑:程序博客网 时间:2024/06/15 10:36
reversed()函数是返回序列seq的反向访问的迭代子。参数可以是列表,元组,字符串,不改变原对象。
1》参数是列表
>>> l=[1,2,3,4,5]
>>> ll=reversed(l)
>>> l
[1, 2, 3, 4, 5]
>>> ll
<listreverseiterator object at 0x06A9E930>
>>> 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
<listreverseiterator object at 0x06A07E10>
>>> list(ll)#第一次
[6, 5, 4, 3]
>>> list(ll)#第二次为空,原因见本文最后
[]
3》参数是元组
>>> t=(4,5,6)
>>> tt=reversed(t)
>>> t
(4, 5, 6)
>>> tt
<reversed object at 0x06A07E50>
>>> tuple(tt)#第一次
(6, 5, 4)
>>> tuple(tt)#第二次为空,原因见本文最后
()
4》参数是字符串
>>> s='cba'
>>> ss=reversed(s)
>>> s
'cba'
>>> ss
<reversed object at 0x06A07E70>
>>> list(ss)#第一次
['a', 'b', 'c']
>>> list(ss)#第二次为空,原因见本文最后
[]
5》参数是字符串
>>> s='1234'
>>> ss=reversed(s)
>>> s
'1234'
>>> ss
<reversed object at 0x06A94490>
>>> ''.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.
总结:reversed()之后,只在第一次遍历时返回值。
- python 内置函数 reversed()
- Python标准库:内置函数reversed(seq)
- python: reverse & reversed 函数
- 3、内置函数sorted()和reversed()使用方法
- Python序列类型常用函数练习:enumerate() reversed() sorted() zip()
- python函数: 内置函数
- python 内置函数
- python内置函数
- Python常用内置函数
- Python常用内置函数
- python内置函数
- python 内置函数
- Python中 内置函数
- python 内置函数
- Python内置函数清单
- python的内置函数
- python模块内置函数
- 【python】内置函数
- 观察者模式
- win7调整游戏全屏
- Linux软连接和硬链接
- DateTime.ToString()的各种日期格式及互转
- 使用stringstream对象简化类型转换
- python 内置函数 reversed()
- Linux GCC内嵌汇编基础知识
- 跟随手指的小球
- 【mybatis源码分析】原理分析之一:从JDBC到Mybatis
- 16进制的转换,随机数排序
- iOS开发中一些常用的方法
- spring常问面试题
- pdo_mysql 安装
- 数据可视化指南(干货)