Scroll through a string list and display the 2 in 2 result

Asked

Viewed 39 times

0

in a certain part of the code, I need to go through a list with string values. However, the display of these values needs to be 2 in 2, instead of 1 to 1. I am using Python version 3.

Example showing 1 to 1:

 seguidores = ["teste", 'teste2', 'teste3', 'teste4', 'teste5']
     
 for i in seguidores:
    print(i)

In the precise case print(i) prints 2 result at a time from the follower list.

2 answers

1

The best solution for this is to use Slices of the list.

seguidores = ["teste", 'teste2', 'teste3', 'teste4', 'teste5']

tamanho = len(seguidores)

# Índice aumenta em 2 a cada iteração
for indice in range(0, tamanho, 2):
  # Mostra os resultados a partir de índice
  # até índice + 2
  print(seguidores[indice : indice + 2])
  • Show adapted to the rest of the code and is running here. Thank you very much

1

seguidores = ["teste", 'teste2', 'teste3', 'teste4', 'teste5', 'teste6', 'teste7', 'teste8', 'teste9']

for i in range(0, len(seguidores), 2):
    try:
        print(f'posicao: {i} e valor:{seguidores[i]} - posicao: {i+1} e valor:{seguidores[i+1]} ')
    except:
        print(f'posicao: {i} e valor:{seguidores[i]}')

inserir a descrição da imagem aqui

  • Show adapted to the rest of the code and is running here. Thank you very much

  • opa, you’re welcome...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.