Home  >  Article  >  Backend Development  >  python中xrange用法分析

python中xrange用法分析

WBOY
WBOYOriginal
2016-06-10 15:15:091491browse

本文实例讲述了python中xrange用法。分享给大家供大家参考。具体如下:

先来看如下示例:

>>> x=xrange(0,8)
>>> print x
xrange(8)
>>> print x[0]
0
>>> print x[7]
7
>>> print x[8]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: xrange object index out of range
>>> x=range(0,8)
>>> print x
[0, 1, 2, 3, 4, 5, 6, 7]
>>> print x[0]
0
>>> print x[8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
range([start,] stop [,step])->list of integers

range()返回一个递增或递减的数字列表,列表的元素值由三个参数决定

start表示列表开始的值,默认为“0”。

stop 表示列表结束的值,该参数不可缺少

参数step表示步长,默认值为“1”。

range()返回的是一个递增或递减的数字列表。

xrange 是一个类,返回的是一个xrange对象。使用xrange()进行遍历,每次遍历只返回一个值。range()返回的是一个列表,一次性计算并返回所有的值。因此,xrange()的执行效率要高于range()

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn