Python xrange() function is used to generate a sequence of integers. This function is part of Python 2. In Python 3, the name has been changed to range() function.
Python xrange()函数用于生成整数序列。 该函数是Python 2的一部分。在Python 3中,名称已更改为range()函数。
Python xrange()语法 (Python xrange() Syntax)
The xrange() function syntax is:
xrange()函数的语法为:
xrange(start, end, step)
- The
start
variable defines the starting number, it’s included in the output sequence of integers. It’s optional and the default value is 0.start
变量定义了起始编号,它包含在整数的输出序列中。 它是可选的,默认值为0。 - The
end
variable defines the ending number, it’s excluded in the output sequence of integers. It’s a mandatory parameter.end
变量定义结束号,它不包含在整数的输出序列中。 这是必填参数。 - The
step
defines the difference between each number in the sequence. It’s optional with the default value is 1. 该step
定义了序列中每个数字之间的差。 它是可选的,默认值为1。 - When only one argument is passed, it’s treated as the
end
variable. 如果仅传递一个参数,则将其视为end
变量。
Python xrange()函数示例 (Python xrange() function examples)
Let’s look at some examples of using xrange() function using Python Interpreter.
让我们看一些使用Python Interpreter使用xrange()函数的示例。
1. xrange()只有结束变量 (1. xrange() with only end variable)
>>> x = xrange(5)
>>> print(type(x))
<type 'xrange'>
>>>
>>> for n in x:
... print(n)
...
0
1
2
3
4
>>>
2. xrange()带有开始和结束值 (2. xrange() with start and end values)
>>> x = xrange(3, 6)
>>> for n in x:
... print(n)
...
3
4
5
>>>
3.具有开始,结束和步骤变量的xrange() (3. xrange() with start, end, and step variables)
>>> x = xrange(3, 10, 2)
>>> for n in x:
... print(n)
...
3
5
7
9
>>>
Python range()与xrange()函数 (Python range() vs xrange() functions)
If you are using Python 2.x version, use the xrange() function to generate a sequence of numbers. If you are on Python 3, then use the range() function since xrange() has been renamed to range() function.
如果使用的是Python 2.x版本,请使用xrange()函数生成一个数字序列。 如果您使用的是Python 3,请使用range()函数,因为xrange()已重命名为range()函数。
翻译自: https://www.journaldev.com/38041/python-xrange-function