So say I have 4 lists of 10 different options each and I want to pick one item from each of the four lists a user specified amount of times. But no repeated outputs. Is this possible? I can't seem to write anything that will not repeat outputs.
Asked
Active
Viewed 3,314 times
0
-
1Why can't you? Python has `set`s built in. – squiguy Apr 28 '13 at 19:34
-
1Post the code that you wrote but didn't work. – Ashwini Chaudhary Apr 28 '13 at 19:34
-
1Can you remove an item from the list once it is picked? – alexn Apr 28 '13 at 19:35
-
Give an example of what you want to do. Its not very clear what you are trying to achieve. – Aditya Apr 28 '13 at 19:37
-
See http://en.wikibooks.org/wiki/Python_Programming/Sets and http://stackoverflow.com/questions/1262955/how-do-i-pick-2-random-items-from-a-python-set . – Owen S. Apr 28 '13 at 21:51
3 Answers
2
population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
population = set(population)
samples = random.sample(population, 3)

kiriloff
- 25,609
- 37
- 148
- 229
2
Lets assume we have these 4
lists:
>>> lists = [range(10*i, 10*(i+1)) for i in range(4)]
>>> lists
[[0, 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]]
First of all, shuffle them:
>>> for lst in lists: random.shuffle(lst)
>>> lists
[[6, 8, 2, 1, 3, 5, 9, 0, 7, 4], [17, 12, 16, 10, 14, 15, 18, 11, 13, 19], [20, 28, 23, 21, 27, 25, 24, 29, 26, 22], [35, 32, 38, 31, 39, 34, 30, 33, 36, 37]]
And then output the values with zip
:
>>> for items in zip(*lists):
print(items)
(6, 17, 20, 35)
(8, 12, 28, 32)
(2, 16, 23, 38)
(1, 10, 21, 31)
(3, 14, 27, 39)
(5, 15, 25, 34)
(9, 18, 24, 30)
(0, 11, 29, 33)
(7, 13, 26, 36)
(4, 19, 22, 37)
If you need only the specified amount of them, just use islice
:
>>> from itertools import islice
>>> for items in islice(zip(*lists),5):
print(items)
(6, 17, 20, 35)
(8, 12, 28, 32)
(2, 16, 23, 38)
(1, 10, 21, 31)
(3, 14, 27, 39)

ovgolovin
- 13,063
- 6
- 47
- 78
0
Something like this should work:
a,b,c,d = initialize_lists()
output_picked_before = set()
n = number_of_experiments()
for i in range(n):
t = pick_random_combination_from_list(a,b,c,d)
while t in output_picked_before:
t = pick_random_combination_from_list(a,b,c,d)
print t
output_picked_before.add(t)

lc2817
- 3,722
- 16
- 40