Python reversed()函数

原文: https://thepythonguru.com/python-builtin-functions/reversed/


于 2020 年 1 月 7 日更新


reversed()函数允许我们以相反的顺序处理项目。 它接受一个序列并返回一个迭代器。

其语法如下:

语法

  1. reversed(sequence) -> reverse iterator
参数 描述
sequence 序列列表字符串,列表,元组等。

这里有些例子:

  1. >>>
  2. >>> reversed([44, 11, -90, 55, 3])
  3. <list_reverseiterator object at 0x7f2aff2f91d0>
  4. >>>
  5. >>>
  6. >>> list(reversed([44, 11, -90, 55, 3])) # reversing a list
  7. [3, 55, -90, 11, 44]
  8. >>>
  9. >>>
  10. >>> list(reversed((6, 1, 3, 9))) # reversing a tuple
  11. [9, 3, 1, 6]
  12. >>>
  13. >>> list(reversed("hello")) # reversing a string
  14. ['o', 'l', 'l', 'e', 'h']
  15. >>>

试试看:

  1. print( reversed([44, 11, -90, 55, 3]) )
  2. print(list(reversed([44, 11, -90, 55, 3]))) # reversing a list
  3. print( list(reversed((6, 1, 3, 9)))) # reversing a tuple
  4. print(list(reversed("hello"))) # reversing a string

为了立即产生结果,我们将reversed()包装在list()调用中。 Python 2 和 Python 3 都需要这样做。

传递给reversed()的参数必须是正确的序列。 尝试传递不保持其顺序(例如dictset)的对象将导致TypeError

  1. >>>
  2. >>> reversed({0, 4, -2, 12, 6})
  3. Traceback (most recent call last):
  4. File "", line 1, in
  5. TypeError: argument to reversed() must be a sequence
  6. >>>
  7. >>>
  8. >>> reversed({'name': 'John', 'age': 20})
  9. Traceback (most recent call last):
  10. File "", line 1, in
  11. TypeError: argument to reversed() must be a sequence
  12. >>>

反转用户定义的对象


若要反转用户定义的对象,该类必须执行下列操作之一:

  1. 实现__len__()__getitem__()方法; 要么
  2. 实现__reversed__()方法

在下面的清单中,CardDeck类实现__len__()__getitem__()方法。 结果,我们可以将reversed()应用于CardDeck实例。

  1. >>>
  2. >>> from collections import namedtuple
  3. >>>
  4. >>> Card = namedtuple('Card', ['rank', 'suit'])
  5. >>>
  6. >>> class CardDeck:
  7. ... suits = ('club', 'diamond', 'heart', 'spades')
  8. ... ranks = tuple((str(i) for i in range(2, 11))) + tuple("JQKA")
  9. ...
  10. ... def __init__(self):
  11. ... self._cards = [Card(r, s) for s in self.suits for r in self.ranks ]
  12. ...
  13. ... def __len__(self):
  14. ... return len(self._cards)
  15. ...
  16. ... def __getitem__(self, index):
  17. ... return self._cards[index]
  18. ...
  19. ... # def __reversed__(self): this is how you would define __reversed__() method
  20. ... # return self._cards[::-1]
  21. ...
  22. ...
  23. >>>
  24. >>> deck = CardDeck()
  25. >>>
  26. >>> deck
  27. <__main__.CardDeck object at 0x7f2aff2feb00>
  28. >>>
  29. >>>
  30. >>> deck[0], deck[-1] # deck before reversing
  31. (Card(rank='2', suit='club'), Card(rank='A', suit='spades'))
  32. >>>
  33. >>>
  34. >>> reversed_deck = list(reversed(deck))
  35. >>>
  36. >>>
  37. >>> reversed_deck[0], reversed_deck[-1] # deck after reversing
  38. (Card(rank='A', suit='spades'), Card(rank='2', suit='club'))
  39. >>>

试一试:

  1. from collections import namedtuple
  2. Card = namedtuple('Card', ['rank', 'suit'])
  3. class CardDeck:
  4. suits = ('club', 'diamond', 'heart', 'spades')
  5. ranks = tuple((str(i) for i in range(2, 11))) + tuple("JQKA")
  6. def __init__(self):
  7. self._cards = [Card(r, s) for s in self.suits for r in self.ranks ]
  8. def __len__(self):
  9. return len(self._cards)
  10. def __getitem__(self, index):
  11. return self._cards[index]
  12. # def __reversed__(self): this is how you would define __reversed__() method
  13. # return self._cards[::-1]
  14. deck = CardDeck()
  15. print(deck)
  16. print( deck[0], deck[-1] ) # deck before reversing
  17. reversed_deck = list(reversed(deck))
  18. print(reversed_deck[0], reversed_deck[-1] ) # deck after reversing