Reputation: 7280
I want to map a given value to a range of values. Eg I am trying to do this for percentage obtained by students in a class. Rather than storing individual percentage I want to store the range of 5. Eg. for 72%, the range would be 70 to 75
. how can i do this.
I want to use dictionary for doing this, but not able to figure out how. Want to do something like:
mydict = {range(0,5):"0 to 5", range(5,10):"5 to 10" ... }
Is there a way of doing this?
EDIT: I want to do this using dictionary
Upvotes: 0
Views: 118
Reputation: 166
If you have a list of numbers (e.g. a list of scores for students), you can use numpy.digitize to map the values into the index of predefined bins of abitary size.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html
For example:
>>>scores = [72, 45, 28, 10, 92]
>>>bins = [0, 40, 55, 60, 70, 80, 90, 100]
>>>numpy.digitize(scores, bins)
array([5, 2, 1, 1, 7])
If you want the bin index to be output to a range in terms of a string, you can make a simple function:
def range_str(index, bins):
return '{} to {}'.format(bins[index-1], bins[index])
e.g.
>>>range_str(5, bins)
'70 to 80'
Upvotes: 0
Reputation: 4951
if you want dictionary, you can do something like:
{k:"{} to {}".format(k - (k%5),5+k - (k%5)) for k in range(MAX_VAL)}
this way, every number will point to the desired string.
However, I believe that @falsetru's answer is better for your needs
Upvotes: 0
Reputation: 368954
You don't need to make a dictionary.
>>> n = 72
>>> base = n // 5 * 5
>>> '{} to {}'.format(base, base+5)
'70 to 75'
Upvotes: 4