Home > Enterprise >  Python to bin calculated results from a function
Python to bin calculated results from a function

Time:12-30

A function is defined to perform some calculation (in this example, it's to sum). The calculated result is to be put into bins (of each 10 as an interval, such as <10, 10-19, 20-29 etc).

What is the smart way to do so? Thank you.

I have a dump way, which created a dictionary to list all the possible calculated results and their bins:

def total(iterable):
    dict = {36: '30 - 40' , 6 : '< 10'}
    total = dict[sum(iterable)]
    return total



candidates = [[11,12,13],[1,2,3]]

for iterable in candidates:
    output = str(total(iterable))
    print (output)

CodePudding user response:

Using a dict will not be feasible, since you possibly cannot have all the options over there, here is how you can do it

candidates = [[11,12,13], [1,2,3]]

for iterable in candidates:
    sum1 = sum(iterable)
    start_bin = int(sum1/10) * 10
    end_bin = start_bin   10
    print('{} - {}'.format(start_bin, end_bin))

You can also make variations in the size of bin by changing how the values are multiplied and divided

  • Related