Remove repeated elements using two lists

Asked

Viewed 183 times

3

How would you remove without using collections and while, only with for. I wanted a search structure element by element, because I already know how to remove this way. So I want to use at least two for chained.

for i in range(len(convidados)):
    pessoas.remove(convidados[i])

I have a good part of the code, working. In the guest list, the elements will be inserted with input(), but left so for practicality purposes.

pessoa= ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]
convidados = ["Felipe","Karen","Matheus","Tulio"]
for i in range(len(pessoa)):
   # achei = 0
    #if 0 < i:
     #   i = 0
    for j in range(len(convidados)):
        if i > len(convidados) or i > len(pessoa):
        #pessoa.index(pessoa[i]):
            i -= 1
        elif pessoa[i] == convidados[j]:

            pessoa.remove(convidados[j])
            #j = achei
            #i=achei

3 answers

3


Here you say you want to remove from the list of people all who were invited. So a very simple way (assuming there are no repeat people) is:

pessoas = ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

for convidado in convidados:
    try:
        pessoas.remove(convidado)
    except ValueError: # convidado não está na lista de pessoas
        pass

print(pessoas) # ['Maria']

I took care to capture the ValueError, because if the guest does not exist in the list of people, this exception is cast. In case, I am ignoring the error and going to the next guest (also changed the name of the list to pessoas - plural - since it is a list with several people; it may seem like a silly detail, but give names better help when programming).


The problem is that pessoas.remove(convidado) only removes the first occurrence of the guest, then the above code only works if the list of people does not have repeated names. For example, if she were:

pessoas = ["Matheus", "Maria", "Felipe", "Tulio", "Karen", "Felipe"]

Only the first "Philip" would be removed, and the result would be ['Maria', 'Felipe'].

Another detail is that this code modifies the list of people. If you do not want this, an alternative is to create another list:

pessoas = ["Matheus", "Maria", "Felipe", "Tulio", "Karen", "Felipe", "Fulano", "Ciclano"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

pessoas_nao_convidadas = [ p for p in pessoas if p not in convidados ]
print(pessoas_nao_convidadas) # ['Maria', 'Fulano', 'Ciclano']

In this case, in addition to creating another list, I also deleted the repetitions by checking if the person is not on the guest list with not in.


If you keep people in order nay for important, you can also use set, which is a structure that does not allow repeatable elements. Thus, simply turn the lists into set's, subtract each other and convert the result into a list:

pessoas = ["Matheus", "Maria", "Felipe", "Tulio", "Karen", "Felipe", "Fulano", "Ciclano"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

# retorna uma lista com 'Maria', 'Fulano' e 'Ciclano', mas não necessariamente nesta ordem
pessoas_nao_convidadas =  list(set(pessoas) - set(convidados))

So I want to use at least two if chained

What for? No need, the above solutions are much simpler, your code was complicating for no reason.

All right that solution with not in should do a linear search on the list, so it is an "implicit loop" within a for, but the point is you don’t need to use two for explicit chained up.

3

Hello,

You can create a new list that will contain the non-repeated elements:

arraySemRepeticao = [] # Lista que terá os elementos não repetidos
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]
pessoa = ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]

todos = convidados + pessoa    # Concatena as duas listas

for i in range(len(todos)):    # Irá percorrer a lista que contém elementos repetidos
    if not todos[i] in arraySemRepeticao:    # Irá verificar se elemento não existe, e se não existir, ele entra nesse if
        arraySemRepeticao.append(todos[i])    # Adiciona no fim da lista o elemento que não existe ainda

print(arraySemRepeticao)

If this is not the solution you are looking for, you can still rely on a new solution with the same logic: I create a new array only with elements that do not yet exist, that is, if it exists, it does not add.

I made a method that would work with infinite lists and that does not create a new list:

def flat(*list):
    newList = []

    for i in range(len(list)):
        for j in range(len(list[i])):
            newList.append(list[i][j])

    return newList


def removeDuplicates(*list):
    flattedList = flat(*list)
    newList = []

    for i in range(len(flattedList)):
        if not flattedList[i] in newList:
            newList.append(flattedList[i])

    return newList


print(removeDuplicates([1, 2, 3], [3, 2, 1], [4, 2, 1])) # [1, 2, 3, 4]

pessoa = ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

print(removeDuplicates(pessoa, convidados)) # ['Matheus', 'Maria', 'Felipe', 'Tulio', 'Karen']

To remove all elements of pessoa who are in convidados, make the following code:

pessoa = ["Matheus", "Maria", "Felipe", "Tulio", "Karen"]
convidados = ["Felipe", "Karen", "Matheus", "Tulio"]

for i in range(len(pessoa)):
    if pessoa[i] in convidados:
        pessoa[i] = None

pessoa = [x for x in pessoa if x is not None] # Remove todos os None
print(pessoa)
  • Yes it is a solution, one of the ways that tbm did not want to use is a new list.

  • I edited and posted a new solution, see if it suits you...

  • Should be removed from the person list the people who were invited, should result the two lists, showing the person list without the chosen guests. My code can remove but does not have a stop condition.

  • I got it, I edited it again with a new solution, see if it suits you :)

  • I understand is that I would love to follow the same structure keeping the code, I even managed to remove when there is more than 1 person, but I would like something to return the index to 0, so I can remove who is left.

1

Hello, I have on account of time developed a very complicated way of getting that with two for’s possible, I proposed this way for logic purposes, and achieve the result without changing much the structure, I quite liked the hktsubo solution mainly, comes very close to what I wanted. Here’s what I could do without running away from the Fors structure:

pessoa= ["Matheus", "Maria", "Felipe", "Tulio", "Karen","belinhaAlmeida"]
convidados = ["Matheus", "Maria", "Tulio", "Karen"]
cont = 0
for i in range(len(pessoa)):

   # achei = 0
    #if 0 < i:
     #   i = 0
    for j in range(len(convidados)):
        if i > len(convidados) or i > len(pessoa)-1:
            i -= 1
       # elif i > pessoa.index(pessoa[j]):
        #    i -= 1
        if len(pessoa) == 1:
            break
                #cont -= 1
        if cont > len(pessoa)-1:
                cont -= 1
        elif pessoa[cont] == convidados[j]:



            pessoa.remove(convidados[j])
            cont = 0
            #j = achei
            #i=achei
    cont += 1
print(pessoa)

Remove anyone I believe.

Browser other questions tagged

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