English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
El tipo range() devuelve una secuencia de números enteros inmutables entre el entero de inicio y el entero de finalización dados.
El constructor de range() tiene dos formas de definición:
range(stop) range(start, stop[, step])
range() utiliza principalmente tres parámetros con el mismo uso en ambas definiciones:
start -entero, desde el cual se devuelve la secuencia entera
stop-para devolver el entero de la secuencia entera a devolver
el rango entero está en1unidadeshasta el punto final.
step (opcional) -entero, que determina el aumento entre cada entero de la secuencia
El objeto de secuencia numérica inmutable devuelto por range() depende de la definición utilizada:
devuelve desde0tostop-1una secuencia numérica de
sistopparanúmeros negativos o 0,entonces devuelve una secuencia vacía.
The return value is calculated by the following formula under the given constraints:
r[n] = start + step*n (for both positive and negative step) where, n >= 0 and r[n] < stop (for positive step) where, n >= 0 and r[n] > stop (for negative step)
(If there is nostep)step defaults to1。Returns fromstarttostop-1ending number sequence.
(Ifstep (If zero) triggerValueErrorException
(If step is not zero) checkValue constraintWhether it meets the constraints and returns the sequence according to the formula.
Returns if the value constraint is not metEmpty Sequence。
# Empty range print(list(range(0))) # Use range(stop) print(list(range(10)) # Use range(start, stop) print(list(range(1, 10))
When running the program, the output is:
[] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9]
Note:We have converted the range toPython list,because range() returns an object similar to a generator, which prints output on demand.
However, the range object returned by the range constructor can also be accessed by its index. It supports both positive and negative indices.
You can access the range object by index in the following way:
rangeObject[index]
start = 2 stop = 14 step = 2 print(list(range(start, stop, step)))
When running the program, the output is:
[2, 4, 6, 8, 10, 12]
start = 2 stop = -14 step = -2 print(list(range(start, stop, step))) # Not satisfied with value constraints print(list(range(start, 14, step)))
When running the program, the output is:
[2, 0, -2, -4, -6, -8, -10, -12] []