Can someone help me subtract one list from another?

Asked

Viewed 54 times

-4

I know it’s simple but I’m beating myself here to do this, I’d like to do a list subtraction in the following way

lista_inicio = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "J", "Q", "K", "A"]
lista_chamada = ["1", "2"]
Lista = []

print(lista_inicio)
print(lista_chamada)
lista = lista_inicio - lista_chamada < **Como faço essa parte?**
print(lista)
  • Boot lista with a superficial copy of lista_inicio thus lista = lista_inicio[:] and eternal for lista_chamada removing from lista its elements and for e in lista_chamada: lista.remove(e) see for example: https://ideone.com/CHnaym

2 answers

0


Do verification by lista_inicio and store all elements that are not in the lista_chamada:


def compara_chamada(lista_i, lista_c):
    return [i for i in lista_i if i not in lista_c]

lista_inicio = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "J", "Q", "K", "A"]
lista_chamada = ["1", "2"]
# é aqui que a mágica acontece: verifico todos da lista_inicio e armazeno
# exceto os que aparecem na lista_chamada
lista = compara_chamada(lista_inicio, lista_chamada)
print(lista)
  • thank you very much man, now I will complicate a little more and you help me to make this function "magica" ?

  • Now let’s say the list has repeated values for example ["1", "1", "2", "3"] when I delete the called list and go all numbers 1 and all 2 right ? how do I go only 1 number instead of going all the same numbers

  • About creating the function, I edited the answer. About repeated values, I didn’t understand... Repeated values are at the beginning or call?

0

The operations you want are set operations. python has its own data structure called set()

See below:

>>> lista_inicio = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "J", "Q", "K", "A"]
>>> lista_chamada = ["1", "2"]
>>> print(set(lista_inicio) - set(lista_chamada))
{'9', '4', 'A', 'Q', '8', '5', 'K', 'J', '7', '3', '6'}

If you need the result to be a list, use:

print(list(set(lista_inicio) - set(lista_chamada)))

Of course you can assign to a variable

lista_resultado = list(set(lista_inicio) - set(lista_chamada)))

As for the repeated items, the structure of the set already treats that

>>> lista = [1, 1, 1, 2, 2, 3, 3, 3, 3]
>>> print(set(lista))
{1, 2, 3}

See below briefly how to add items in set()

>>> conjunto = set([1, 2, 3])

>>> print(conjunto)
{1, 2, 3}

>>> conjunto.add(4)

>>> print(conjunto)
{1, 2, 3, 4}

>>> conjunto.add(4)

>>> print(conjunto)
{1, 2, 3, 4}

>>> conjunto.add(1)

>>> print(conjunto)
{1, 2, 3, 4}

Notice that the second 4 and subsequently the second 1, nay were included.

In time: The response marked as a solution on 07/22/2021 is not performative.

Browser other questions tagged

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