python 之 内置函数大全[通俗易懂]

python 之 内置函数大全[通俗易懂]一、罗列全部的内置函数戳:https://docs.python.org/2/library/functions.html二、range、xrange(迭代器)无论是range()还是xrang

大家好,又见面了,我是你们的朋友全栈君。

一、罗列全部的内置函数

  戳:https://docs.python.org/2/library/functions.html

二、range、xrange(迭代器)

  无论是range()还是xrange()都是Python里的内置函数。这个两个内置函数最常用在for循环中。例如:

  1. >>> for i in range(5):
  2. … print i
  3. … 
  4. 0
  5. 1
  6. 2
  7. 3
  8. 4
  9. >>> for i in xrange(5):
  10. … print i
  11. … 
  12. 0
  13. 1
  14. 2
  15. 3
  16. 4
  17. >>>

range()和xrange() 在Python 2里是两种不同的实现。但是在Python 3里,range()这种实现被移除了;
保留了xrange()的实现,且将xrange()重新命名成range()。

首先,我们来看Python 2里range()。它是一个内置函数,这个函数用于创建整数等差数列。因此它
常被用于for循环。下面是range()的官方帮助文档。

  1. Help on built-in function range in module __builtin__:
  2. range(…)
  3. range(stop) -> list of integers
  4. range(start, stop[, step]) -> list of integers
  5. Return a list containing an arithmetic progression of integers.
  6. range(i, j) returns [i, i+1, i+2, …, j-1]; start (!) defaults to 0.
  7. When step is given, it specifies the increment (or decrement).
  8. For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
  9. These are exactly the valid indices for a list of 4 elements.
  10. (END)

从官方帮助文档,我们可以看出下面的特性:
1、内置函数(built-in)
2、接受3个参数分别是start, stop和step(其中start和step是可选的,stop是必需的)
3、如果没有指定start,默认从0开始(Python都是从0开始的)
4、如果没有指定step,默认step是1。(step不能是0,如果指定step为0,“ValueError: range() step argument must not be zero”
      将会被抛出。
额外的特性:
1、当step为正数时,start应该小于stop,否则将生成[ ],即空数列。

  1. >>> range(-3)
  2. []
  3. >>> range(5, 1)
  4. []
  5. >>> range(1,1)
  6. []

2、当step为负数时,start应该大于stop,否则将生成[ ],即空数列。
这两个特性说明range()可以生成递增和递减的数列。
下面是range()生成数列的例子:

  1. >>> range(5)
  2. [0, 1, 2, 3, 4]
  3. >>> range(1,8,3)
  4. [1, 4, 7]
  5. >>> range(0, -10)
  6. []
  7. >>> range(0, -10, -2)
  8. [0, -2, -4, -6, -8]
  9. >>>

接下来看看xrange()。 xrange()虽然也是内置函数,但是它被定义成了Python里一种类型(type),
这种类型就叫xrange。我们从Python 2的interactive shell里很容易看到这点。

  1. >>> range
  2. <built-in function range>
  3. >>> xrange
  4. <type ‘xrange’>
  5. >>>

我们再来看看xragne的官方帮助文档:

  1. Help on class xrange in module __builtin__:
  2. class xrange(object)
  3. | xrange(stop) -> xrange object
  4. | xrange(start, stop[, step]) -> xrange object
  5. |
  6. | Like range(), but instead of returning a list, returns an object that
  7. | generates the numbers in the range on demand. For looping, this is
  8. | slightly faster than range() and more memory efficient.
  9. |
  10. | Methods defined here:
  11. |
  12. | __getattribute__(…)
  13. | x.__getattribute__(‘name’) <==> x.name
  14. |
  15. | __getitem__(…)
  16. | x.__getitem__(y) <==> x[y]
  17. |
  18. | __iter__(…)
  19. | x.__iter__() <==> iter(x)
  20. |
  21. | __len__(…)
  22. | x.__len__() <==> len(x)
  23. |
  24. | __reduce__(…)
  25. |
  26. | __repr__(…)
  27. | x.__repr__() <==> repr(x)
  28. |
  29. | __reversed__(…)
  30. | Returns a reverse iterator.
  31. |
  32. | ———————————————————————-
  33. | Data and other attributes defined here:
  34. |
  35. | __new__ =
  36. | T.__new__(S, …) -> a new object with type S, a subtype of T
  37. (END)

从文档里可以看出,xrange和range的参数和用法是相同的。只是xrange()返回的不再是一个数列,而是一个
xrange对象。这个对象可以按需生成参数指定范围内的数字(即元素)。由于xrange对象是按需生成单个的
元素,而不像range那样,首先创建整个list。所以,在相同的范围内,xrange占用的内存空间将更小,xrange
也会更快。实际上,xrange由于是在循环内被调用时才会生成元素,因此无论循环多少次,只有当前一个元素
占用了内存空间,且每次循环占用的都是相同的单个元素空间。我们可以粗略的认为,相同n个元素的话,range占
用的空间是xrange的n倍。因此,在循环很大情况下,xrange的高效率和快速将表现的很明显。我们可以用timeit
来测试一下range和xrange的执行时间。

  1. >>> timeit.timeit(‘for i in range(10000000): pass’,number=1)
  2. 0.49290895462036133
  3. >>> timeit.timeit(‘for i in xrange(10000000): pass’,number=1)
  4. 0.2595210075378418

在大量循环的条件下,可以看到xrange的高效率是很明显的。

总结一下:
1、range()返回整个list。
2、xrange()返回的是一个xrange object,且这个对象是个iterable。
3、两者都用与for循环。
4、xrange()占用更少的内存空间,因为循环时xrange()只生成当前的元素,不像range()一开始就成生成完整的list。
这就是在Python 2里range和xrange的相同点和区别。

那么在Python 3里,我们在前面提到了range()被移除了,xrange()被重新命名成了range()。它们之间有区别吗?
请看下面的代码
Python 2的xrange()

  1. Python 2.7.6 (default, Dec 5 2013, 23:54:52) 
  2. [GCC 4.6.3] on linux2
  3. Type “help”, “copyright”, “credits” or “license” for more information.
  4. >>> x = xrange(5)
  5. >>> x
  6. xrange(5)
  7. >>> x[:]
  8. Traceback (most recent call last):
  9.   File “”, line 1, in <module>
  10. TypeError: sequence index must be integer, not ‘slice’
  11. >>> x[-1]
  12. 4
  13. >>> list(x)
  14. [0, 1, 2, 3, 4]
  15. >>> dir(x)
  16. [‘__class__’, ‘__delattr__’, ‘__doc__’, ‘__format__’, ‘__getattribute__’, ‘__getitem__’, ‘__hash__’, ‘__init__’, ‘__iter__’, ‘__len__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’]
  17. >>>

Python 3的range()

  1. Python 3.3.4 (default, Feb 23 2014, 23:07:23) 
  2. [GCC 4.6.3] on linux
  3. Type “help”, “copyright”, “credits” or “license” for more information.
  4. >>> x = range(5)
  5. >>> x
  6. range(0, 5)
  7. >>> x[:]
  8. range(0, 5)
  9. >>> x[:3]
  10. range(0, 3)
  11. >>> list(x)
  12. [0, 1, 2, 3, 4]
  13. >>> x[-1]
  14. 4
  15. >>> dir(x)
  16. [‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’,’__repr__’, ‘__reversed__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘count’, ‘index’, ‘start’, ‘step’, ‘stop’]
  17. >>>

很明显,range object在Python里增加了新的attributes,‘count’, ‘index’, ‘start’, ‘step’, ‘stop’
且能支持slicing。Python 3的range()在xrange()的基础上变得更强大了。

请理解下面这句话:
The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the startstop and step values, calculating individual items and subranges as needed).

到这里,我们应该比较清楚range和xrange的区别了

三、yield

def fab(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        # print b
        a, b = b, a + b
        n = n + 1
c = fab(10)
print(c.__next__())  # python 3.x 已经没有 next()方法
print(c.__next__())
print(c.__next__())
print(c.__next__())
# for i in fab(10):
#     print(i)

python 之 内置函数大全[通俗易懂]

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/156040.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 【阅读笔记】数据分析思维:分析方法和业务知识

    【阅读笔记】数据分析思维:分析方法和业务知识这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML图表FLowchart流程图导出与导入导出导入欢迎使用Markdown编辑器你好!这是你第一次使用Markdown编辑器所展示的欢迎页。如果你想学习如何使用Mar

    2022年6月7日
    93
  • python读取图像的几种方法_python图像识别教程

    python读取图像的几种方法_python图像识别教程python读取图像的几种方式本文介绍几种基于python的图像读取方式:基于PIL库的图像读取、保存和显示基于opencv-python的图像读取、保存和显示基于matplotlib的图像读取、保存和显示基于scikit-image的图像读取、保存和显示基于imageio的图像读取、保存和显示安装方式基本使用pip即可:pipinstallpillowpipinstallscikit-imagepipinstallmatplotlibpipinstallopen

    2022年9月12日
    1
  • com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure一、前言在学习AndroidAndroid入门案例(二)——JDBC连接MySql数据库使用jdbc方式连接本地数据库时报错:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:CommunicationslinkfailureThelastpacketsentsuccessfullytotheserve……

    2022年6月23日
    30
  • linux 安装Jenkins和配置(完整详细版)

    linux 安装Jenkins和配置(完整详细版)Linux 环境下安装 JDK 完整详细版 Linux 搭建 Maven 仓库 完整详细版

    2025年7月28日
    2
  • python3.9多线程_python多线程没用

    python3.9多线程_python多线程没用什么是线程?线程也叫轻量级进程,是操作系统能够进行运算调度的最小单位,它被包涵在进程之中,是进程中的实际运作单位。线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其

    2022年7月28日
    12
  • PyCharm 软件 离线 安装 插件「建议收藏」

    PyCharm 软件 离线 安装 插件「建议收藏」代理配置:https://blog.csdn.net/github_35160620/article/details/53209324 插件离线下载地址:http://plugins.jetbrains.com/ 2.下载插件安装插件1、下载插件:2、安装插件:settings-&gt;plugins-&gt;installpluginfromd…

    2022年8月28日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号