remove duplicates by prespetiva of tuples

Asked

Viewed 73 times

0

I have this code working, yet I wanted to do it from the perspective of the tuples. Can assist?

def remove_repetidos(lst):
    lista = [] #lista vazia
    for i in lst:
        if i not in lista:
            lista.append(i)
    lista.sort() #ordenada a lista por ordem ascendente
    return lista
  • At what point exactly would you like to apply the tuples?

  • Meanwhile I made another one that’s not working and I’m not sure why.

  • def sensas(lst): lst_unica = [i for n, i in enumerate(lst_com_unicos) if i not in lst_com_unicos[n + 1:]] for lst_resulta_unica in lst_unica: Return lst_resulta_unica

  • This other code seems to be wrong. You use a variable lst_com_unicos that has not been defined.

  • sorry I’m new in python, I thought he assumed. I’ll redo, I put here

  • def sensas(lst): lst_com_unicos = () lst_unica = [i for n, i in enumerate(lst_com_unicos) if i not in lst_com_unicos[n + 1:]] for lst_resulta_unica in lst_unica: Relstturn_resulta_unica

Show 1 more comment

1 answer

1


You cannot use tuples to do the same as you did with the list because the tuples are immutable and thus cannot add new values. To add a new value in the tuple it is necessary to create a new tuple with the current values plus the new one and this addition is made from an auxiliary structure.

For example, it is possible to do all the logic using lists and just return as tuple:

def remove_repetidos(lst):
    lista = [] #lista vazia
    for i in lst:
        if i not in lista:
            lista.append(i)
    lista.sort() #ordenada a lista por ordem ascendente
    return tuple(lista)

And to create a new tuple by adding the new value would look something like:

def remove_repetidos(lst):
    unicos = tuple()
    for valor in lst:
        if valor not in unicos:
            unicos += (valor,)
    return unicos

But note the fact that even though it looks like it’s only modifying the tuple you’re actually creating a new tuple and overwriting the old one.

The simplest way to remove duplicate items from a sequence is by using the set, as can be seen in Remove Repeated Integers List in Python

  • Thank you. That’s right. However I needed sito fucnionasse for both integers and text. remove_repeats((a,b,c,d,a,b,c,d,d,c,b)) and in this case tells me that 'a' is not defined. Do I have to validate the input parameters?

  • @Pipocainsuflada No, only use strings correctly. The strings are defined in quotation marks: ('a', 'b', 'a', 'a', 'c', ...)

  • Thank you for that

Browser other questions tagged

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