Iteración hacia atrás en Python

La iteración de números se realiza mediante técnicas de bucle en Python. Hay muchas técnicas en Python que facilitan los bucles. A veces necesitamos realizar el bucle hacia atrás y tener abreviaturas para hacerlo puede ser muy útil. Vamos a discutir ciertas formas en que esto se puede hacer.

Método n.° 1: Usar invertida() La forma más sencilla de realizar esto es usar la función invertida para el ciclo for y la iteración comenzará desde el lado posterior que el conteo convencional. 

Python3

# Python3 code to demonstrate
# backward iteration
# using reversed()
 
# Initializing number from which
# iteration begins
N = 6
 
# using reversed() to perform the back iteration
print ("The reversed numbers are : ", end = "")
for num in reversed(range(N + 1)) :
    print(num, end = " ")
Producción

The reversed numbers are : 6 5 4 3 2 1 0 

 Método n.º 2: Usar rango (N, -1, -1) Esta tarea en particular también se puede realizar usando la función de rango convencional que, si se proporciona con el tercer argumento, realiza el salto y el segundo argumento se usa para comenzar desde atrás. 

Python3

# Python3 code to demonstrate
# backward iteration
# using range(N, -1, -1)
 
# Initializing number from which
# iteration begins
N = 6
 
# using reversed() to perform the back iteration
print ("The reversed numbers are : ", end = "")
for num in range(N, -1, -1) :
    print(num, end = " ")
Producción

The reversed numbers are : 6 5 4 3 2 1 0 

Método n.º 3: uso de la sintaxis de división Esta tarea en particular también se puede realizar utilizando la sintaxis de división que se utiliza para invertir la lista. Lo usamos para invertir la clase de rango en el ciclo for y luego realizamos la iteración hacia atrás.

Python3

# # Python3 code to demonstrate
# # backward iteration
# # using slice syntax
 
# # Initializing number from which
# # iteration begins
N = 6
 
 
# Using slice syntax perform the backward iteration
k = range(N+1)[::-1]
print("The reversed numbers are : ",end='')
for i in k:
    print(i, end=' ')
Producción

The reversed numbers are : 6 5 4 3 2 1 0 

Publicación traducida automáticamente

Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *