-1

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.

Underoos
  • 4,708
  • 8
  • 42
  • 85
1a2a3a 4a5a6a
  • 103
  • 1
  • 8
  • 1
    Check this out https://stackoverflow.com/questions/10048069/what-is-the-most-pythonic-way-to-pop-a-random-element-from-a-list – Underoos Apr 04 '19 at 09:06

5 Answers5

0

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']
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

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]
D.Morrissey
  • 114
  • 8
0

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:]
Philipp F
  • 417
  • 2
  • 11
0
>>> 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']
sunnky
  • 175
  • 6
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – undetected Selenium Apr 04 '19 at 09:29
0

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

Lucas
  • 395
  • 1
  • 11