认识reversed单词

reversed 英[rɪ'vɜ:st] 美[rɪ'vɜst]

adj. 颠倒的;相反的;(判决等)撤销的

v. 颠倒(reverse的过去式和过去分词);翻转

help(reversed)

  1. Help on class reversed in module builtins:
  2.  
  3. class reversed(object)
  4. | reversed(sequence) -> reverse iterator over values of the sequence
  5. |
  6. | Return a reverse iterator
  7. |
  8. | Methods defined here:
  9. |
  10. | __getattribute__(self, name, /)
  11. | Return getattr(self, name).
  12. |
  13. | __iter__(self, /)
  14. | Implement iter(self).
  15. |
  16. | __length_hint__(...)
  17. | Private method returning an estimate of len(list(it)).
  18. |
  19. | __new__(*args, **kwargs) from builtins.type
  20. | Create and return a new object. See help(type) for accurate signature.
  21. |
  22. | __next__(self, /)
  23. | Implement next(self).
  24. |
  25. | __reduce__(...)
  26. | Return state information for pickling.
  27. |
  28. | __setstate__(...)
  29. | Set state information for unpickling.

reversed的英文解释

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

reversed()函数的输入时任意一个序列,返回一份倒序后的序列副本。通常用于for循环需要倒序循环时。

eg:

  1. seq = [1, 2, 3, 4, 5, 6, 7, 8]
  2. for item in reversed(seq):
  3. print(item, end=" ")

结果:

  1. 8 7 6 5 4 3 2 1

reversed()的功能:翻转对象

  • 翻转函数reversed()调用参数类中的__reversed__()函数。
  • 函数功能是反转一个序列对象,将其元素从后向前颠倒构建成一个新的迭代器

reversed()的应用

应用1: 序列的倒序循环

  1. seq1 = list(range(8))
  2. print("seq1为: {}".format(seq1))
  3. for i in reversed(seq1):
  4. print(i, end=' ')

结果:

  1. seq1为: [0, 1, 2, 3, 4, 5, 6, 7]
  2. 7 6 5 4 3 2 1 0
  1. seq2 = ['a', 'b', 'c', 'd']
  2. print("seq2为: {}".format(seq2))
  3. for i in reversed(seq2):
  4. print(i, end=' ')

结果:

  1. seq2为: ['a', 'b', 'c', 'd']
  2. d c b a

应用2:

如果一个对象不存在__reversed__()方法,那么,reversed()会调用__len__()和__getitem__()生成倒序序列。

  1. class MySeq():
  2. def __len__(self):
  3. return 6
  4. def __getitem__(self, index):
  5. return 'y{0}'.format(index)
  6.  
  7. for item in reversed(MySeq()):
  8. print(item, end=', ')

结果:

  1. y5, y4, y3, y2, y1, y0,

应用3:

如果我们需要定制或者优化倒序过程,我们只需重写__reversed__()方法。

  1. class MySeq():
  2. def __len__(self):
  3. return 6
  4. def __getitem__(self, index):
  5. return 'y{0}'.format(index)
  6. class MyReversed(MySeq):
  7. def __reversed__(self):
  8. return 'hello, bright!'
  9.  
  10. for item in reversed(MyReversed()): # 调用重写的__reversed__()方法。
  11. print(item, end=' ')

结果:

  1. h e l l o , b r i g h t !

或者:

  1. class MySeq():
  2. def __len__(self):
  3. return 6
  4. def __getitem__(self, index):
  5. return 'y{0}'.format(index)
  6. class MyReversed(MySeq):
  7. def __reversed__(self):
  8. return reversed('hello, bright!')
  9.  
  10. for item in reversed(MyReversed()):
  11. print(item, end=' ')

结果:

  1. ! t h g i r b , o l l e h

应用4:

如果reversed()的参数不是一个序列对象,我们应该为该对象定义一个__reversed__方法,这个时候就可以使用reversed()函数了。

  1. class MyScore:
  2. def __init__(self, name, *args):
  3. self.name = name
  4.  
  5. self.scores = []
  6. for value in args:
  7. self.scores.append(value)
  8.  
  9. def __reversed__(self):
  10. self.scores = reversed(self.scores)
  11.  
  12. x = MyScore("bright", 66, 77, 88, 99, 100)
  13.  
  14. print('我的名字: {0}, \n我的成绩: {1}'.format(x.name, x.scores))
  15. print('我的成绩按降序排列:{}'.format(list(reversed(x.scores))))

结果:

  1. 我的名字: bright,
  2. 我的成绩: [66, 77, 88, 99, 100]
  3. 我的成绩按降序排列:[100, 99, 88, 77, 66]

知识在于点点滴滴的积累,我会在这个路上Go ahead,

有幸看到我博客的朋友们,若能学到知识,请多多关注以及讨论,让我们共同进步,扬帆起航。

后记:打油诗一首

适度锻炼,量化指标

考量天气,设定目标

科学锻炼,成就体标

高效科研,实现学标


Python3内置函数——reversed() = 翻转我的世界的更多相关文章

  1. python3内置函数大全(顺序排列)

    python3内置函数大全 内置函数 (1)abs(),   绝对值或复数的模 1 print(abs(-6))#>>>>6 (2)all() 接受一个迭代器,如果迭代器的所有 ...

  2. python3内置函数大全

    由于面试的时候有时候会问到python的几个基本内置函数,由于记不太清,就比较难受,于是呕心沥血总结了一下python3的基本内置函数 Github源码:        https://github. ...

  3. Python内置函数reversed()用法分析

    Python内置函数reversed()用法分析 这篇文章主要介绍了Python内置函数reversed()用法,结合实例形式分析了reversed()函数的功能及针对序列元素相关操作技巧与使用注意事 ...

  4. Python3内置函数、各数据类型(int/str/list/dict/set/tuple)的内置方法快速一览表

    Python3内置函数 https://www.runoob.com/python3/python3-built-in-functions.html int https://www.runoob.co ...

  5. python3内置函数详解

    内置函数 注:查看详细猛击这里 abs() 对传入参数取绝对值 bool() 对传入参数取布尔值, None, 0, "",[],{},() 这些参数传入bool后,返回False ...

  6. python 之 python3内置函数

    一. 简介 python内置了一系列的常用函数,以便于我们使用,python英文官方文档详细说明:点击查看, 为了方便查看,将内置函数的总结记录下来. 二. 使用说明 以下是Python3版本所有的内 ...

  7. python3 内置函数详解

    内置函数详解 abs(x) 返回数字的绝对值,参数可以是整数或浮点数,如果参数是复数,则返回其大小. # 如果参数是复数,则返回其大小. >>> abs(-25) 25 >&g ...

  8. Python3 内置函数补充匿名函数

    Python3 匿名函数 定义一个函数与变量的定义非常相似,对于有名函数,必须通过变量名访问 def func(x,y,z=1): return x+y+z print(func(1,2,3)) 匿名 ...

  9. python3 内置函数

    '''iter()和next()'''# lst = [1, 2, 3]# it = iter(lst)# print(it.__next__())# print(it.__next__())# pr ...

随机推荐

  1. 【转】Shell编程基础篇-下

    [转]Shell编程基础篇-下 1.1 条件表达式 1.1.1 文件判断 常用文件测试操作符 常用文件测试操作符 说明 -d文件,d的全拼为directory 文件存在且为目录则为真,即测试表达式成立 ...

  2. Linux串口—struct termios结构体【转】

    转自:https://blog.csdn.net/yemingzhu163/article/details/5897156 一.数据成员 termios 函数族提供了一个常规的终端接口,用于控制非同步 ...

  3. phantomjs 中如何使用xpath

    function getNodeInfo(inputcsvPath) { var htmlnodeInfo = page.evaluate(function () { //_Ltg var XPATH ...

  4. C:malloc/calloc/realloc/alloca内存分配函数

    原文地址:http://www.cnblogs.com/3me-linux/p/3962152.html calloc(), malloc(), realloc(), free(),alloca() ...

  5. Qt5.8 在windows下mingw静态编译

    官方对编译一些条件介绍:https://doc.qt.io/qt-5/windows-requirements.html 在默认情况下,用QtCreator编译程序时,使用的是动态编译.编译好的程序在 ...

  6. Golang依赖管理工具:glide从入门到精通使用

    这是一个创建于 2017-07-22 05:33:09 的文章,其中的信息可能已经有所发展或是发生改变. 介绍 不论是开发Java还是你正在学习的Golang,都会遇到依赖管理问题.Java有牛逼轰轰 ...

  7. CNN中各种各样的卷积

    https://zhuanlan.zhihu.com/p/29367273 https://zhuanlan.zhihu.com/p/28749411 以及1*1卷积核:https://www.zhi ...

  8. 神经网络,前向传播FP和反向传播BP

    1 神经网络 神经网络就是将许多个单一“神经元”联结在一起,这样,一个“神经元”的输出就可以是另一个“神经元”的输入.例如,下图就是一个简单的神经网络: 我们使用圆圈来表示神经网络的输入,标上“”的圆 ...

  9. django----查看数据库中的sql语句

    加载setting.py 文件中 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console ...

  10. poj3696 欧拉函数引用

    不知道错在哪里,永远T /* 引理:a,n互质,则满足a^x=1(mod n)的最小正整数x0是φ(n)的约数 思路:求出d=gcd(L,8) 求出φ(9L/d)的约数集合,再枚举约数x,是否满足10 ...