This method is commonly used with weighted random number generation method, the idea is to sum the weight value total, in 0 with the weight and total to obtain a random number rd, traverse the weight dictionary, accumulate its weight value weight_sum, when Rd is less than or equal to Weight_sum, Returns the current weight key value, as shown in the example code:
Import randomdef random_weight (Weight_data): _total = sum (Weight_ Data.values ()) # weight summation _random = random.uniform (0, _total) # in 0 with weights and before getting a random number _curr_sum = 0 _ret = None try: _keys = weight_data.iterkeys () # using iterkeys in python2.x except attributeerror: _keys = weight_data.keys () # using keys in python3.x for _k in _keys: _curr_sum += data[_k] # in Traversal, Accumulate current weight value if _random <= _curr_sum: # returns the weight when the random number <= the current weight and key _ret = _k break return _ret
The transfer value is a dictionary, key is the random data to get, key for its weight, such as {' A ': ten, ' B ': ' C ': 50}
A simple implementation of Python with weighted random numbers