Exclude items from another list

Asked

Viewed 36 times

-2

I wanted to know how I could delete from a list, the elements from another list (which will be used #for training) and stay with only the elements for testing, contained within the initial list.

I tried to leave an executable:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Created on Fri Mar 27 15:13:49 2020

# import random  
import random 


lista = [1,2,3,4,5,6,7,8,9,10] 
print("Lista:", lista)

# Fixar uma semente e dado uma lista escolher parte dela, exemplo, 7 ids aleatorios
random.seed(0.72)   # Setar uma semente
idtrain = list(set(random.sample(lista, 7)))
print("Train animals:", idtrain) 

# indexar
#index = list.index(idtrain)
#list(x.keys()).index(idtrain)
#print("The index of idtrain:", index)


# Excluir os ids que estao nos treinos para ficar somente os ids dos testes
#tentativa 1
idteste = lista.extend(idtrain)

#tentativa 2
idteste = lista.remove(idtrain)

#tentativa 3
if(idtrain in lista):
    idteste = lista.remove(idtrain)

#tentativa 4
idteste = list(filter(lambda a: a != idtrain, lista))

#tentativa 5
while idtrain in lista:
    lista.remove(idtrain)

# tentativa 6
for i in idtrain:
    print(i)
    idteste = lista.remove(i)

print(idteste)

print("Test animals:", idteste)

1 answer

0

You can use list comprehension:

idteste = [item for item in lista if item not in idtrain]

Another possible method is the use of Sets. Sets can be subtracted from each other to get the different items:

idteste = list( set(lista) - set(idtrain) )

Of course, as set’s have no order, and do not allow repetition, it should be noted in this method that you will lose duplicate elements of the original list, and also lose the order in which they appear.

Related question here (in English)

Browser other questions tagged

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