'Random generator that removes items from a list after picking
I have a list with 48 items. I want to randomly pick out 3 of those items, then remove those three items from the list. After that, randomly pick 3 new items. I wish to loop this 16 times until all the items are removed.
I've tried a for loop. But I can't figure out how to remove those specific items that was randomly selected from the list. I'm pretty new at both Python and programming. Help would be much appreciated.
list_ = ['Pink', 'Red', 'Green', 'Darkgreen', 'Blue', 'Skyblue'] * 8
loop_ = np.arange(0, 16)
for i in loop:
print(random.sample(list_, 3))
Solution 1:[1]
np.arange(1,16) is of 15 length, but you want to loop 16 times. Also, avoide using list.remove when there are duplicates in the list, even though probably it will not cause troubles in your specific problem. Finally, as said, avoid using 'list' as name as it's already used by Python.
Here is my suggestion, working on indexes and using list.pop(0) method:
l = ['Pink', 'Red', 'Green', 'Darkgreen', 'Blue', 'Skyblue'] * 8
for i in range(16):
item = random.sample(range(len(l)), 3)
for k in sorted(item, reverse=True):
l.pop(k)
print(l)
#[]
Solution 2:[2]
you can also do the list.pop(index) method.
import random as rd
import numpy as np
lst = ['Pink', 'Red', 'Green', 'Darkgreen', 'Blue', 'Skyblue'] * 8
loop = np.arange(1,16)
for i in loop:
for k in range(0,3):
item = lst.pop(rd.choice(range(0,len(lst))))
print(item)
.pop(index) method does two things. It returns the element at the given index of a list. It then removes that element from the list.
Inside of the .pop() function we have the following: a random choice of a number (which is the index) the choice is a list of numbers between 0 and the length of the list (exclusive).
Solution 3:[3]
import random
my_list = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25,26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48
]
for i in range(16):
removed_list = random.sample(my_list, 3)
for item in removed_list:
my_list.remove(item)
print(my_list)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | A.Karwowski |
| Solution 3 | pzaenger |
