Python reversed反转序列并生成可迭代对象

作者:lincappu 时间:2022-07-10 04:51:41 

英文文档:

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 at 0).

反转序列生成新的可迭代对象

说明:

1. 函数功能是反转一个序列对象,将其元素从后向前颠倒构建成一个新的迭代器。


>>> a = reversed(range(10)) # 传入range对象
>>> a # 类型变成迭代器
<range_iterator object at 0x035634E8>
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

>>> a = ['a','b','c','d']
>>> a
['a', 'b', 'c', 'd']
>>> reversed(a) # 传入列表对象
<list_reverseiterator object at 0x031874D0>
>>> b = reversed(a)
>>> b # 类型变成迭代器
<list_reverseiterator object at 0x037C4EB0>
>>> 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:
     self.scores.append(value)

>>> a = Student('Bob',78,85,93,96)
>>> reversed(a) # 实例不能反转
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
 reversed(a)
TypeError: argument to reversed() must be a sequence
>>> type(a.scores) # 列表类型
<class 'list'>

# 重新定义类型,并为其定义__reversed__方法
>>> class Student:
 def __init__(self,name,*args):
   self.name = name
   self.scores = []
   for value in args:
     self.scores.append(value)
 def __reversed__(self):
   self.scores = reversed(self.scores)

>>> a = Student('Bob',78,85,93,96)
>>> a.scores # 列表类型
[78, 85, 93, 96]
>>> type(a.scores)
<class 'list'>

>>> reversed(a) # 实例变得可以反转
>>> a.scores # 反转后类型变成迭代器
<list_reverseiterator object at 0x0342F3B0>
>>> type(a.scores)
<class 'list_reverseiterator'>

>>> list(a.scores)
[96, 93, 85, 78]

来源:https://www.cnblogs.com/lincappu/p/8144961.html

标签:Python,reversed,反转,序列
0
投稿

猜你喜欢

  • python网络爬虫实现个性化音乐播放器示例解析

    2021-10-06 10:14:51
  • pip安装python库时报Failed building wheel for xxx错误的解决方法

    2021-12-12 04:55:53
  • 实现div可编辑的常见方法

    2007-11-06 12:02:00
  • 如何处理好网页色彩搭配

    2007-08-10 13:22:00
  • 正则表达式学习笔记

    2008-04-15 07:44:00
  • Numpy与Pytorch 矩阵操作方式

    2021-11-19 01:10:07
  • Python内置的HTTP协议服务器SimpleHTTPServer使用指南

    2021-11-22 08:11:12
  • 正确认识MySQL对服务器端光标的限制

    2008-12-03 15:52:00
  • Python虚拟环境库virtualenvwrapper安装及使用

    2023-12-28 22:11:53
  • MySQL转义字符

    2011-06-19 16:06:04
  • js关于 byval 与 byref 的区别

    2007-10-13 10:48:00
  • Pytorch模型微调fine-tune详解

    2021-06-17 07:29:00
  • Pycharm+Python+PyQt5使用详解

    2021-08-20 06:39:25
  • Python Django模板之模板过滤器与自定义模板过滤器示例

    2023-10-31 20:37:48
  • discuz 2.0整合asp系统,用户添加函数

    2011-04-02 11:08:00
  • Python脚本传参数argparse模块的使用

    2023-02-28 23:07:21
  • tensorflow查看ckpt各节点名称实例

    2021-03-26 14:04:49
  • Numpy数组转置的实现

    2022-10-16 09:15:34
  • Python之两种模式的生产者消费者模型详解

    2021-07-31 17:44:02
  • Python模拟脉冲星伪信号频率实例代码

    2023-02-12 06:01:08
  • asp之家 网络编程 m.aspxhome.com