英文文件:
reversed
(seq)
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 at0
).
反轉序列生成新的可迭代物件
說明:
1. 函式功能是反轉乙個序列物件,將其元素從後向前顛倒構建成乙個新的迭代器。
>>> 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__方法。
# 型別student沒有定義__reversed__方法>>> class student:
def __init__(self,name,*args):
self.name = name
self.scores =
for value in args:
>>> 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) # 列表型別
# 重新定義型別,並為其定義__reversed__方法
>>> class student:
def __init__(self,name,*args):
self.name = name
self.scores =
for value in args:
def __reversed__(self):
self.scores = reversed(self.scores)
>>> a = student('bob',78,85,93,96)
>>> a.scores # 列表型別
[78, 85, 93, 96]
>>> type(a.scores)
>>> reversed(a) # 例項變得可以反轉
>>> a.scores # 反轉後型別變成迭代器
>>> type(a.scores)
>>> list(a.scores)
[96, 93, 85, 78]
python3 6中內建函式變化
最近學習發現,python3.x比之與python2.x,許多內建要麼不再是內建函式,要麼已經改變呼叫方式。因此決定把已知的變化寫下,以作參考。目前reduce函式已經移到functools模組中,呼叫前需要先導入functools模組 import functools functools.redu...
Python3 6內建函式 5 bin
bin x convert an integer number to a binary string.the result is a valid python expression.if x is not a python int object,it has to define an index m...
Python3 6 List內建方法
list 的內建方法 li 1,2 3,4 print li li 1 list 1,2 3,4 接收乙個iterable,可迭代即可 print li 0 可以使用下標訪問元素 print li print li 1,2,3,4,aabb print li 1,2,3,4,aabb 1234 de...