I have a dictionary where the keys represent groups, and the values are a list of elements (for simplicity let's assume the values are integers).
An example of such a dictionary, d
, is:
d = {2: [0, 1, 7, 8, 9], 1: [2, 4], 4: [3], 3: [5, 6]}
I wish to sample this dictionary multiple times randomly, where the sample will consist of a random sampling of a single element from the first group, a single element from the second, etc.
Simple output examples are:
[9, 2, 3, 5]
[1, 2, 3, 6]
[7, 4, 3, 6]
...
I can iterate over the dictionary, d
, M
times and iterate over the keys and sample 1 element, I was wondering if there is a simpler method, hopefully, more efficient as it will be a part of a larger more complex algorithm.
The naive approach is:
ll = []
for i in range(10):
tmp = []
for k, l in d.items():
tmp.append(random.choice(l))
ll.append(tmp)
print(ll) # [[5, 6, 9, 7], [8, 4, 3, 7], [2, 1, 3, 7], [5, 1, 3, 7], [0, 4, 3, 7], [2, 1, 3, 7], [2, 6, 9, 7], [2, 1, 9, 7], [8, 4, 9, 7], [2, 1, 9, 7]]
I'm not strict about the dictionary, I can use other structures as well but the logic stays the same.
Would appreciate some help.
Aucun commentaire:
Enregistrer un commentaire