How to remove repeated numbers from a python list

Asked

Viewed 1,969 times

0

Hello guys I’m doing a course in python and currently I Completed this exercise.

Write the remove_repeated function that takes as a parameter a list of integer numbers, checks whether such a list has repeated elements and removes them. The function should return a list corresponding to the first list, without repeating elements. The returned list should be sorted.

If anyone can give a hint or a solution I am grateful

numeros = (input("Digite uma lista com números inteiros: "))
list = numeros.split()   # transforma em listas

print("Você digitou os seguintes números: ")
print(list)

def remove_repetidos(list):

    sorted(set(list)) # ordena e une todos os números em vez de tá repetido, somente haverá um número representando o conjunto "set"
    print("O resultado é")
    print()
    print( sorted(set(list)))

remove_repetidos(list)
  • What is your doubt, I did a test and its function removed the duplicates and ordered... It is not actually returning, but part of the code is working.

  • Hello I type a list for example [1,2,2,2,2,2,2,2,2,2,2,4,4,4,4,4,44,4,4,4,4,4] and he returns me the same list instead of returning [1,2,4,44]

7 answers

4

numeros = (input("Digite uma lista com números inteiros: "))
lista = numeros.split()   # transforma em listas

print("Você digitou os seguintes números: ")
print(lista)


def remove_repetidos(lista):

  lista_numeros_unicos = []

  for numero in lista:
    if(numero in lista_numeros_unicos): #Verifica se o atual elemento existe na lista original
      pass #Se existir não faz nada
    else:
      lista_numeros_unicos.append(numero) #Se não existir, adiciona com o comando append() o numero na lista

  return lista_numeros_unicos

# Ordena a lista
lista = sorted(remove_repetidos(lista))

print("\n A lista sem numeros repetidos é: ")
print(lista)

Basically you just need to create an auxiliary list, which in case was the lista_numeros_unicos, it receives, the non-repeated numbers that are in the list. Note that I used the operator in.

Obs: list is a reserved word, be careful.

Link to online compiler test, Repl.it

  • Thank you very much for the answer I understood very well what you expressed and I liked your remark :) but no harm I typed [1,2,2,2,2,2,2,2,2,2,2,4,4,4,4,4,44,4,4,4,4,4] and I got back ['[1,2,2,2,2,2,2,2,2,2,2,4,4,4,4,4,44,4,4,4,4,4]'] and it was to have as a return [1,2,4]

  • This is because you are typing the commas, which makes a single element, for example, '2,2,3,5,2,2' instead of '2','2','3','5','2','2', if you use only space, it will work correctly. However, if you need to type the commas, I can see if I can change the code.

  • 1

    I accept the help :) with the code by typing the commas. And I tried other ways and the old code picked up normally without commas, but as it is necessary I could not do :(

1

Your function is sorting the list and removing the repeated numbers perfectly. What you need to do now is just use the return to return the new list.

def remove_repetidos(list_):
    return sorted(set(list_))

number_list = [7, 1, 2, 8, 5, 1, 7, 2, 8]
new_list = remove_repetidos(number_list)
  • Hello keeps returning the same value

  • def remove_repetidos(lista): return sorted(set(lista)) 
 number_list= lista
 nova_lista = remove_repetidos(number_list)
 print("O resultado é")
 print()
 print( sorted(set(lista)))

remove_repetidos(lista)

1

# se utilizar as duas funções abaixo, que funcionam como decoradores...

def remove_espacos_de_cada_elemento_em_uma_lista_de_strings(func):
    def remover_espacos(lista):
        nova_lista = [x.strip() for x in lista]
        return func(nova_lista)
    return remover_espacos


def remove_elementos_repetidos_em_uma_lista(func):
        def filtrar(lista):
            for i in lista:
                if lista.count(i) > 1:
                   lista.remove(i)
                   filtrar(lista)
            return lista

        def lista_com_elementos_unicos(lista):
            lista_unica = filtrar(lista)
            return func(lista_unica)

        return lista_com_elementos_unicos

#### poderá decorar qualquer função e ter o retorno de qualquer objeto, com elementos únicos(lista, tuplas, dicionários...)

Example:

@remove_espacos_de_cada_elemento_em_uma_lista_de_strings
def retirar_espacos_de_cada_elemento_em_uma_lista_de_strings(lista):
    return lista
  • Thanks for the contribution, but it didn’t work :(

1

Reading the comments understood what is happening, when typing the list you use the literal python list syntax itself to insert it as input and the answers use a list syntax whose items are separated by space and the input is not bounded by brackets.

So I’m not gonna hold down the function remove_repetidos() because the other answers have already explained the subject and then I will define it in a way that visually goes unnoticed:

remove_repetidos = lambda l: list(sorted(set(l)))

I’ll focus more on the console input treatment.
Let’s take three entrees:

  • [3,2,5,2,4,0,5,2,3]
  • 3,2,5,2,4,0,5,2,3
  • 3 2 5 2 4 0 5 2 3

From just looking we can conclude:

  1. All these entries can be understood as being a list typed by the user.

  2. They may or may not be started and finished by square brackets [].

  3. The content that matters is its numerical elements and not the separators.

Aware of this we can treat the user input by removing all that is not numerical and taking advantage of these non-numerical characters to group the digits and thus separate the numbers to recomporm them a list of integers.

To remove what is not numerical and separate the input into numerical strings I used a Regular Expression and method re.split() that divides a string by the occurrences of a pattern.
The standard used was (?a)\D+ where: - (?to) equals the constant re.ASCII what force to pattern \D the ASCII capture. - \D+ means capturing one or more of everything that is not an ASCII digit.

To remove the empty captures that can be generated by duplicate separators or separators present at the beginning and end of the input I used the built-in function filter() objectionable None as a filter parameter.
To convert numeric strings into integers I used the built-in function map to apply the constructor of the class int each element previously returned by filter().

import re

numeros = input("Digite uma lista com números inteiros: ")

#Cria uma lista de inteiros apartando as strings numérica de 
#tudo aquilo que não for número decimal
lista = list(map(int, filter(None, re.split('(?a)\D+', numeros ))))

print("Você digitou os seguintes números: ")
print(lista)

#Cria a função remove_repetidos que cria e ordena um set a #partir de uma lista
remove_repetidos = lambda l: list(sorted(set(l)))

print("Sua lista filtrada e ordenada: ")
print(remove_repetidos(lista))

Test the code in the Repl.it: https://repl.it/repls/WickedMintcreamDaemon

Output example:

Digite uma lista com números inteiros: [1,2,2,2,2,2,2,2,2,2,2,4,4,4,4,4,44,4,4,4,4,4]
Você digitou os seguintes números: 
[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 44, 4, 4, 4, 4, 4]
Sua lista filtrada e ordenada: 
[1, 2, 4, 44]

Output example:

Digite uma lista com números inteiros: 7 6 7 6 5 8 9
Você digitou os seguintes números: 
[7, 6, 7, 6, 5, 8, 9]
Sua lista filtrada e ordenada: 
[5, 6, 7, 8, 9]

0

numeros = input("Digite uma lista com números inteiros: ")
lista = numeros.split()   # transforma em listas

print("Você digitou os seguintes números: ")
print(lista)

def remove_repetidos(lista_qualquer):
    lista_sem_elementos_repetidos = [] 
    lista_qualquer.sort() # ordena a lista_qualquer
    for numero in lista_qualquer: 
        if numero not in lista_sem_elementos_repetidos: # Se o número não estiver na lista
            lista_sem_elementos_repetidos.append(numero) # Adiciona o número a lista
    return lista_sem_elementos_repetidos # Retorna a lista_sem_elementos_repetidos

print(remove_repetidos(lista))
  • Why sort the input list instead of the final list?

  • Don’t just post code without explaining purpose, strategy, idea, and so on

0

To resolve this issue we must follow the following steps:

  1. Capture the values;
  2. Store them in a list;
  3. Pass this list as argument to the function remove_repetidos();
  4. Remove the repeated values;
  5. Display the list without repeated values.

So I developed the following script:

def remove_repetidos(lis):
    li_sem_repeticoes = list()
    for item in lis:
        if item not in li_sem_repeticoes:
            li_sem_repeticoes.append(item)
    return li_sem_repeticoes


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

print(f'\033[32mA lista sem repetições é:\n{remove_repetidos(lista)}\033[m')

Note that when we run this script we receive the following message: Digite os valores da lista: . Right now we must type all the values of the list in the same line, separated for a single space and press enter.

After inserting the values the script will take the entered values and assemble a list. Then this list is sent as argumento for the function remove_repetidos. Getting there, the block for will traverse the target list through all elements. During each of the passages (interactions), it is checked whether the turn element is contained in the list li_sem_repeticoes. If no, this item is added to the list li_sem_repeticoes and subsequently display the same ordered in ascending form.

Example 1

If we type...

1 2 2 2 2 2 2 2 2 2 2 4 4 4 4 4 44 4 4 4 4 4

... and press enter, we’ll have the following exits...

A lista sem repetições é:
[1, 2, 4, 44]

Note that in the example 1 were typed 22 elements, in addition, the 17th element of this list is 44. This element only occurs 1 only once in that list. Therefore, this element is displayed in the original list without repetitions.

Example 2

If we type...

1 2 2 2 2 2 2 2 2 2 2 4 4 4 4 4 4 4 4 4 4

...and press enter, we will have the following exits...

A lista sem repetições é:
[1, 2, 4]

Note that in the example 2 were typed 21 elements, moreover, there is no element 44. Therefore, the original list without repetitions does not have the element 44.

-2

Using sets (sets), develop a Python code that takes numbers or words (strings), warning when there is repeated element insertion attempt. Initially, the user chooses how many elements the set will store and whether the elements will be numbers or words (which must be tested before they are inserted into the set). At the end, print the set and the amount of attempts of repeated non-valid inserts. Variables, data structures and functions must have the names and surnames of the student(s) (of the group).

Browser other questions tagged

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