ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Python `reversed()`函数 > 原文: [https://thepythonguru.com/python-builtin-functions/reversed/](https://thepythonguru.com/python-builtin-functions/reversed/) * * * 于 2020 年 1 月 7 日更新 * * * `reversed()`函数允许我们以相反的顺序处理项目。 它接受一个序列并返回一个迭代器。 其语法如下: **语法**: ```py reversed(sequence) -> reverse iterator ``` | 参数 | 描述 | | --- | --- | | `sequence` | 序列列表字符串,列表,元组等。 | 这里有些例子: ```py >>> >>> 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'] >>> ``` 试试看: ```py 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`。 ```py >>> >>> 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 >>> ``` ## 反转用户定义的对象 * * * 若要反转用户定义的对象,该类必须执行下列操作之一: 1. 实现`__len__()`和`__getitem__()`方法; 要么 2. 实现`__reversed__()`方法 在下面的清单中,`CardDeck`类实现`__len__()`和`__getitem__()`方法。 结果,我们可以将`reversed()`应用于`CardDeck`实例。 ```py >>> >>> 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')) >>> ``` 试一试: ```py 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 ``` * * * * * *