Identify repeated elements in list with Python

2

The list I made should read the repeated values from a list and show their positions, but it did not work correctly

lista = []

listaRepetido = True
for i in range(4):
    lista.append(int(input("Numero: ")))

for i in lista:
    for j in range(2,i):
        if ((i == j) == 0):
            listaRepetido = False
            break

    if listaRepetido:
            posicao = lista.index(i)
            print("Numero %i na %i° posiçaõ" % (i, posicao + 2))
    listaRepetido = True    
    
asked by anonymous 28.06.2017 / 22:44

1 answer

5

Using collections.defaultdict makes this calculation much simpler:

from collections import defaultdict

# Define a lista de volares:
lista = [3, 2, 4, 7, 3, 8, 2, 3, 8, 1]

# Define o objeto que armazenará os índices de cada elemento:
keys = defaultdict(list);

# Percorre todos os elementos da lista:
for key, value in enumerate(lista):

    # Adiciona o índice do valor na lista de índices:
    keys[value].append(key)

# Exibe o resultado:
for value in keys:
    if len(keys[value]) > 1:
        print(value, keys[value])

The result is:

2 [1, 6] 
3 [0, 4, 7] 
8 [5, 8]
  

See working at Ideone .

    
29.06.2017 / 03:27