how it returns the indices of a python list

Asked

Viewed 1,516 times

-1

I have the list:

lista = [0,0,0,0]

How can I return the contents of this list so it stays that way:

Índice: 0 1 2 3
item:   0 0 0 0
def f1():
    #funcão criar um post, cria um novo post com 0 likes 
    post.append(0)
    print(print(),'O post nro.',len(post),' tem sido criado.')    
    print('A lista de postagens é a seguinte:\nÍndice: 0\nLikes: 0')
    input('Aperte Enter para para voltar')

Goal

'print'

The post no. 3 has been created.

The list of posts is as follows:

Índice: 0 1 2 3
Likes: 0 0 0 0

Press R to go back

4 answers

3

There is no method to retrieve the contents of a list, why these indexes are always sequential number, starting at zero.

does not have "different indexes".

If you need individual indexes, you can use builtin range: it will also give you a sequence of numbers, starting at zero by default.

But, if you want to show on the screen the indexes, for example, in a loop is - the natural in Python is to use builtin enumerate. It can be used in a for and will return you the index, along with the element in that index:

for indice, elemento in enumerate(lista): ...

Only if you really want to post the contents on a top line, and the elements on a bottom line, the thing complicates: you can’t naturally keep going between the top line and the bottom line in Python (nor any other language, if the output is in the terminal): Voce would essentially have to create a table in memory, generate the output of each cell of the table and print this table. in this simple example, it is easier to do a for range to print the numbers, and another with the list elements, to print the elements themselves.

The most natural is simply printing vertically:

print("indicet - elemento")
for indice, elemento in enumerate(lista):
    print (f"{indice:<10}{elemento}")

(Here I used a printable formatting rule that says to align the index to the left, with 10 spaces, using the :<10 inside the key)

to do horizontally, as you want, just do:

...
print(f"Índices: {list(range(len(lista))}")
print(f"Likes  : {lista}")
  • thanks jsbueno manage to understand now and managed to do horizontally

1

If the purpose of your code is to just solve an exercise or kill curiosity about a certain type of display this solution is not better suited for you, because even the code looking simple it does use of a sophisticated resource that is the DataFrame. Would be the same than to kill a cockroach with a shotgun.

If your code is part of something larger and this data set will later be modified, operationalized, analyzed, recalculated and reexibido you can have the possibility to use a DataFrame and method DataFrame.rename_axis to tabulate your data.

from pandas import DataFrame

l = [2, 4, 6, 3, 8]

#Cria um DataFrame sobre um dicionário índice/valor sobre a lista l com um cabeçalho # 
#de índices e uma única linha, de nome likes e do tipo inteiro, contendo os valores correspondentes
df = DataFrame(dict(enumerate(l)), index=["likes:"], dtype=int)

#Ajusta o nome do eixo das colunas 
df = df.rename_axis("índice:", axis="columns")

print(df)

Exit:

índice:  0  1  2  3  4
likes:   2  4  6  3  8

Code in Repl.it: https://repl.it/repls/ElectronicEuphoricFrontpage

0

Use the the function enumerate:

Input

lista = [0,0,0,0]

print(f"Índices:", end=" ")

for chave, _ in enumerate(lista):
    print(chave, end=" ")

print("\n")

print(f"Valores:", end=" ")

for _, valor in enumerate(lista):
    print(valor, end=" ")

Output

Índices: 0 1 2 3 

Valores: 0 0 0 0

0

Whoa, whoa, buddy, whoa! Come on: if you want to print the contents of a list named as a list, You can do the following:

lista = [0,0,0,0]
lista_indices = []
for i in lista:
   lista_indices.append(lista.index(i))
print(lista_indices)

I hope I helped :D

  • thank Allen only that it is returning [0,0,0,0] ie returns the items from the list not the Dice

  • Voce has to assign the indexes to another list and call it in place

Browser other questions tagged

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