Last active
August 30, 2022 12:36
-
-
Save RicardoTurco/5a77734e05bea3fa0da8968f00ec54cc to your computer and use it in GitHub Desktop.
Python: eliminando elementos repetidos (através de ITERAÇÃO e SET)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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