Created
October 18, 2011 14:13
-
-
Save yamatt/1295517 to your computer and use it in GitHub Desktop.
select random key that is weighted by it's value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import choice | |
d = { | |
'foo1': 1, | |
'foo2': 5, | |
'foo3': 3 | |
} | |
choice([k for k in d for x in range(d[k])]) | |
## think of it as | |
L = [] | |
for k in d: | |
for x in range(d[k]): | |
L.append(k) | |
choice (L) | |
# L ends up end up as this list: | |
['foo1', 'foo2', 'foo2', 'foo2', 'foo2', 'foo2', 'foo3', 'foo3', 'foo3'] | |
""" | |
By using choice you obviously have the most chance of it selecting 'foo2' in the region of 5 in 9 chance. | |
Memory usage is high for higher numbers so don't use this method for lots of choices or more precise chances of probability. | |
It will also only work with integers. | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By using choice you obviously have the most chance of it selecting 'foo2' in the region of 5 in 9 chance.
Memory usage is high for higher numbers so don't use this method for lots of choices or more precise chances of probability.
It will also only work with integers.