本文提供了使用Python内置函数reversed ()的示例。 分享仅供参考。 具体如下。
reversed ) )函数是返回序列seq的反向访问的迭代器。 参数是列表、元组和字符串,不更改原始对象。
1 )参数为清单l=[1、2、3、4、5]
ll=反转(l ) )
LL
[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=反转(l ) )
LL
[ 3,4,5,6 ]
ll
list(ll ) #第一次
[ 6,5,4,3 ]
list(ll ) #第二次为空。 理由请参照正文的末尾
[]
3 )自变量为元组t=(4、5、6 )
TT=反转(t ) )
t
(4、5、6 ) )。
tt
tuple(TT ) #首次
(六、五、四) )。
tuple(TT ) #第二次为空。 理由请参照正文的末尾
()
4 )自变量为字符串s='cba '
ss=反转(s ) )
s
' cba '
ss
list(ss ) #首次
[a ',b ',c']
list(ss ) #第二次为空。 理由请参照正文的末尾
[]
5 )参数为字符串s='1234 '
ss=反转(s ) )
s
' 1234 '
ss
'.join(ss ) #第一次
' 4321 '
'.join(ss ) #第二次为空。 理由请参照正文的末尾
''
为什么在reversed (之后是第二个for循环、第二个list )、第二个tuple )或第二个join )中获得的结果为空? 让我用第二个例子具体说明一下。
that ' sbecausereversedcreatesaniterator,whichisalreadyspentwhenyou ' recalling list (ll ) for the second time。
thereasonisthatllisnotthereversedlistitself,butalistreverseiterator.sowhenyoucallist (ll ) the first time, ititeratesoverllandcreatesanewlistfromtheitemsoutputfromthatiterator.whenyoudoitasecondtime, llisstilltheoriginaliteratorandhasalreadygonethroughalltheitems,so it doesn't iterate over anything,resulting in an empty list。
试着编辑并翻译一下:
这是因为反向创建了在第二次调用列表(LL )时已经使用的迭代器。
其理由是,ll不是反转列表本身,而是列表的反向迭代器。 因此,kddxh将首次调用列表(ll ),遍历ll,并创建一个从项目中输出迭代器的新列表。 即使kddxh再次运行,ll仍然是原始迭代器,并经历了所有项目,因此不会遍历任何内容。 这将是空列表。
总结: reversed () )之后,仅在第一次遍历时返回值。
对Python相关内容感兴趣的读者可参阅本网站的文章《Python函数使用技巧总结》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python文件与目录操作技巧汇总》、0103010、0103010
本文希望对大家的Python编程有所帮助。