Python reversed()
函数
原文: https://thepythonguru.com/python-builtin-functions/reversed/
于 2020 年 1 月 7 日更新
reversed()
函数允许我们以相反的顺序处理项目。 它接受一个序列并返回一个迭代器。
其语法如下:
语法:
reversed(sequence) -> reverse iterator
参数 | 描述 |
---|---|
sequence |
序列列表字符串,列表,元组等。 |
这里有些例子:
>>>
>>> reversed([44, 11, -90, 55, 3])
<list_reverseiterator object at 0x7f2aff2f91d0>
>>>
>>>
>>> list(reversed([44, 11, -90, 55, 3])) # reversing a list
[3, 55, -90, 11, 44]
>>>
>>>
>>> list(reversed((6, 1, 3, 9))) # reversing a tuple
[9, 3, 1, 6]
>>>
>>> list(reversed("hello")) # reversing a string
['o', 'l', 'l', 'e', 'h']
>>>
试试看:
print( reversed([44, 11, -90, 55, 3]) )
print(list(reversed([44, 11, -90, 55, 3]))) # reversing a list
print( list(reversed((6, 1, 3, 9)))) # reversing a tuple
print(list(reversed("hello"))) # reversing a string
为了立即产生结果,我们将reversed()
包装在list()
调用中。 Python 2 和 Python 3 都需要这样做。
传递给reversed()
的参数必须是正确的序列。 尝试传递不保持其顺序(例如dict
和set
)的对象将导致TypeError
。
>>>
>>> reversed({0, 4, -2, 12, 6})
Traceback (most recent call last):
File "", line 1, in
TypeError: argument to reversed() must be a sequence
>>>
>>>
>>> reversed({'name': 'John', 'age': 20})
Traceback (most recent call last):
File "", line 1, in
TypeError: argument to reversed() must be a sequence
>>>
反转用户定义的对象
若要反转用户定义的对象,该类必须执行下列操作之一:
- 实现
__len__()
和__getitem__()
方法; 要么 - 实现
__reversed__()
方法
在下面的清单中,CardDeck
类实现__len__()
和__getitem__()
方法。 结果,我们可以将reversed()
应用于CardDeck
实例。
>>>
>>> from collections import namedtuple
>>>
>>> Card = namedtuple('Card', ['rank', 'suit'])
>>>
>>> class CardDeck:
... suits = ('club', 'diamond', 'heart', 'spades')
... ranks = tuple((str(i) for i in range(2, 11))) + tuple("JQKA")
...
... def __init__(self):
... self._cards = [Card(r, s) for s in self.suits for r in self.ranks ]
...
... def __len__(self):
... return len(self._cards)
...
... def __getitem__(self, index):
... return self._cards[index]
...
... # def __reversed__(self): this is how you would define __reversed__() method
... # return self._cards[::-1]
...
...
>>>
>>> deck = CardDeck()
>>>
>>> deck
<__main__.CardDeck object at 0x7f2aff2feb00>
>>>
>>>
>>> deck[0], deck[-1] # deck before reversing
(Card(rank='2', suit='club'), Card(rank='A', suit='spades'))
>>>
>>>
>>> reversed_deck = list(reversed(deck))
>>>
>>>
>>> reversed_deck[0], reversed_deck[-1] # deck after reversing
(Card(rank='A', suit='spades'), Card(rank='2', suit='club'))
>>>
试一试:
from collections import namedtuple
Card = namedtuple('Card', ['rank', 'suit'])
class CardDeck:
suits = ('club', 'diamond', 'heart', 'spades')
ranks = tuple((str(i) for i in range(2, 11))) + tuple("JQKA")
def __init__(self):
self._cards = [Card(r, s) for s in self.suits for r in self.ranks ]
def __len__(self):
return len(self._cards)
def __getitem__(self, index):
return self._cards[index]
# def __reversed__(self): this is how you would define __reversed__() method
# return self._cards[::-1]
deck = CardDeck()
print(deck)
print( deck[0], deck[-1] ) # deck before reversing
reversed_deck = list(reversed(deck))
print(reversed_deck[0], reversed_deck[-1] ) # deck after reversing