Identify repeated elements in Python list

Asked

Viewed 14,794 times

3

The list I made should read the repeated values of 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    
  • if ((i == j) == 0):, what this should do?

  • compare the element of i with the element of j, and then check if it is equal to zero

2 answers

10


Using collections.defaultdict is much simpler this calculation:

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 displayed result is:

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

See working on Ideone.

  • in case you displayed all values, but I need to show only the repeated ones, q in this your list would be the values 3, 2, 8.

  • 1

    @Juniorsilva true, corrected already.

  • Show, bro!! Thanks a lot :)

1

Another interesting way is using the method Counter library Collections. In this case, the code would be:

from collections import Counter

lista = list(map(int, input('Digite os valores: ').split()))
c = Counter(lista)

for numero, repeticoes in c.items():
    if repeticoes > 1:
        result = [indice for indice, item in enumerate(lista) if item == numero]
        print(f'O número "{numero}" se repete nos índices {result}.')

Note that when we execute this code we receive the following message: Digite os valores: . Right now we must type all the values, in the same line, separated for a single space and press Enter.

OBS: With this code you can enter as many numbers as you want in your list.

At this time the block for will travel the object c.items() and whether the number of repetitions of a particular number is greater than 1, the list shall be assembled result. This list will be formed by List Comprehensions and, later, will be displayed the result composed by the number that has more than 1 occurrence and the respective indexes of its occurrences.

Browser other questions tagged

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