I use the numpy.random.choice method
to draw a sample from a list.
The entries in the list are short dicts and look like
{'name': 'SomeName', 'strength': 0.75},
{'name': 'SomeName', 'strength': 0.25},
...
I want to use the 'strength' value (between 0 and 1) as a probability indicator.
To use
drawResults = choice(data, drawCount, p=resultProb)
I have to create the resultProb list which has to sum up to 1
So I came up with a function:
def makeProbabilities(data) -> list:
probResult = []
totalScore = sum(item['strength'] for item in data) # calculate in sum of all 'strength' values
for item in data:
if item['strength'] > 0:
value = (100.0/totalScore)*item['strength'] #how much is this strength in relation to the total
value2 = (1.0/100)*value #how much is the result above in relation to 1
probResult.append(value2)
else:
probResult.append(0.0)
return probResult
That seems to work, it just have a very small rounding error on the result (the sum is like 1.0000000001) but the numby.choice method does accept it.
But I have the strong impression that this solution is a bit awkward, un-pythonique and perhaps not very efficient on large data sets.
I am just discovering python so I am a bit lost with all the information concerning this language.
Any feedback on that is very welcome.