本文目录
英文文档
reversed()
小结
英文文档
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).
reversed()
1. 函数功能是反转一个序列对象,将其元素从后向前颠倒构建成一个新的迭代器。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16>>> a = reversed ( range ( 10 ) ) # 传入range对象
>>> a # 类型变成迭代器
>>> list (a )
[ 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ]
>>> a = [ 'a' , 'b' , 'c' , 'd' ]
>>> a
[ 'a' , 'b' , 'c' , 'd' ]
>>> reversed (a ) # 传入列表对象
>>> b = reversed (a )
>>> b # 类型变成迭代器
>>> list (b )
[ 'd' , 'c' , 'b' , 'a' ]
2. 如果参数不是一个序列对象,则其必须定义一个__reversed__方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44# 类型Student没有定义__reversed__方法
>>> class Student:
def __init__ ( self ,name ,*args ):
self. name = name
self. scores = [ ]
for value in args:
self. scores. append (value )
>>> a = Student ( 'Bob' , 78 , 85 , 93 , 96 )
>>> reversed (a ) # 实例不能反转
Traceback (most recent call last ):
File "" , line 1 , in
reversed (a )
TypeError: argument to reversed ( ) must be a sequence
>>> type (a. scores ) # 列表类型
< class 'list' >
# 重新定义类型,并为其定义__reversed__方法
>>> class Student:
def __init__ ( self ,name ,*args ):
self. name = name
self. scores = [ ]
for value in args:
self. scores. append (value )
def __reversed__ ( self ):
self. scores = reversed ( self. scores )
>>> a = Student ( 'Bob' , 78 , 85 , 93 , 96 )
>>> a. scores # 列表类型
[ 78 , 85 , 93 , 96 ]
>>> type (a. scores )
< class 'list' >
>>> reversed (a ) # 实例变得可以反转
>>> a. scores # 反转后类型变成迭代器
>>> type (a. scores )
< class 'list_reverseiterator' >
>>> list (a. scores )
[ 96 , 93 , 85 , 78 ]
小结
希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,我都希望你留言和我们进行交流、讨论。
欢迎关注微信公众号,谢谢大家支持:AiryData。
转载请注明:数据之美 Python3.6内置函数(54)——reversed()
喜欢 (0) or 分享 (0)