# 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
```
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象