I am trying to delete elements from original list whenever I sample from it.
list_a = ["a", "b", "c", "d"]
list_b = np.random.choice(list_a, 2)
When I np.random.choice
, I want list_a
to be a list without the elements of list_b
.
I am trying to delete elements from original list whenever I sample from it.
list_a = ["a", "b", "c", "d"]
list_b = np.random.choice(list_a, 2)
When I np.random.choice
, I want list_a
to be a list without the elements of list_b
.
You could have a list excluded the elements of list_a
that exist in list_b
:
Using list comprehension:
list_a = ["a", "b", "c", "d"]
list_b = np.random.choice(list_a, 2)
print([x for x in list_a if x not in list_b])
print(list_b)
OUTPUT:
['c', 'd']
['b' 'a']
This can be done using the remove() python has.
You can read more about the remove() here: https://www.programiz.com/python-programming/methods/list/remove
import numpy as np
list_a = ["a", "b", "c", "d"]
list_b = np.random.choice(list_a, 2)
for i in list_b:
list_a.remove(i)
print list_a
print list_b
RESULTS:
list_a = [a, c]
list_b = [b, d]
You can shuffle the list and then split it, giving you the sampled elements and the remaining elements.
import numpy as np
list_a = ["a", "b", "c", "d"]
np.random.shuffle(list_a)
list_b, list_a = list_a[:2], list_a[2:]
>>> import numpy as np
>>> list_a = ["a", "b", "c", "d"]
>>> _ = [list_a.remove(i) for i in np.random.choice(list_a, 2) if i in list_a]
>>> list_a
['b', 'd']
Rather then using the choice
function you can get a random integer as index and use pop()
on the list:
import random
list_a = ["a", "b", "c", "d"]
def select_and_remove(list, items):
sample = []
for i in range(0, items)
sample.append(list.pop(random.randint(0, len(list)-1))
return list, sample
Then run:
list_a, sample = select_and_remove(list_a, 2)
Note however, this will throw a ValueError
if the list is empty or if you want to select more items as available