Skip to content

Instantly share code, notes, and snippets.

@RicardoTurco
Last active August 30, 2022 12:36
Show Gist options
  • Save RicardoTurco/5a77734e05bea3fa0da8968f00ec54cc to your computer and use it in GitHub Desktop.
Save RicardoTurco/5a77734e05bea3fa0da8968f00ec54cc to your computer and use it in GitHub Desktop.
Python: eliminando elementos repetidos (através de ITERAÇÃO e SET)
# a) "dict.fromkeys(<lista>)", MANTENDO A ORDEM OS ELEMENTOS:
lista = [1, 1, 2, 1, 3, 4, 3, 6, 7, 6, 7, 8, 10 ,9]
lu = list(dict.fromkeys(lista))
# Resultado
lu
[1, 2, 3, 4, 6, 7, 8, 10, 9]
# b) ELIMINANDO ATRAVÉS DE "ITERAÇÃO"
lista = [1, 1, 2, 1, 3, 4, 3, 6, 7, 6, 7, 8, 10 ,9]
l = []
# percorrendo a "lista",
# caso o item não exista em "l" , adiciona-o,
# dessa forma os itens "repetidos" não entram ...
for i in lista:
if i not in l:
l.append(i)
# Resultado
l
[1, 2, 3, 4, 6, 7, 8, 10, 9]
# podemos realizar uma "ordenação" (opcional)
l.sort()
# Resultado
l
[1, 2, 3, 4, 6, 7, 8, 9, 10]
# c) ELIMINANDO ATRAVÉS DA FUNÇÃO SET()
lista = [1, 1, 2, 1, 3, 4, 3, 6, 7, 6, 7, 8, 10 ,9]
# ao utilizar a função "set()", os itens repetidos são eliminados,
# transformamos o resultado (set) em uma lista "list" ...
lu = list(set(lista))
# o único "detalhe" da função SET(), é que implicitamente ela
# realiza uma "ordenação" ...
# Resultado
lu
[1, 2, 3, 4, 6, 7, 8, 9, 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment