Reputation: 21
Thanks in advance for any advice! I have a random group of numbers that need to be sorted into groups based on their range... I could use some advice how to do this...thanks in advance
So, I imagine the code works like this: Take a list of 100 random numbers ranging from 0-1000 Split the range (from 0-1000) into x number of groups (say 10 groups: 0-100,100-200, 200-300 etc...) For i in this list test if its in group 1 if true add this to a list if not test consecutive groups
the thing is the number of groups should be a variable that can be adjusted and the subsequent lists should be updated accordingly to the division of the range...
import random as r
#create list of random integers
ranInteger = []
#length of list of random integers
for i in range (10):
ranInt = r.randint(0,1000)
ranInteger.append(ranInt)
print "ranInteger =", ranInteger
#find bounds of random list of integers
maxL = max(ranInteger)
minL = min(ranInteger)
print "maxL =", maxL
print "minL =", minL
#find range of random list of integers
rangeL = maxL - minL
print "rangeL =", rangeL
#divide range to create grouping value
divRange = 10
grpValue = (rangeL / divRange)
print "grpValue =", grpValue
#make List of grouping values
grpL =[]
r2 = range (minL, maxL, int (grpValue))
grpL.append (r2)
print "grpL =", grpL
#tests each number
indexl = []
for j in ranInteger:
#test each range
if i >= ranInteger[s] and i< ranInteger [s+1]) or (s==0)):
print indexl
#to be honest I have no idea how to sort this list into different groups
#and to have the lists with groups update if the group division is changed
#how can I dynamically create lists based on the value of other objects?
#so i can say divRange = 10 make 10 lists with values grouped in there
#but if the user changes this divRange = 20 then it automatically makes 20
#lists with new groups contained within
# I would also like these same lists but with the index of the grouped items
instead of the actual number
thank you!!! - E
Upvotes: 2
Views: 1695
Reputation: 10936
The usual way to solve this type of problem is to write a function that does the work, and call that function with different input parameters. Like this:
def make_bins(x_in, n_bins):
"""
x_in is a list of numbers
n_bins is how many bins to separate x into
returns a list of length of n_bins, each element of which is a list
"""
x_min = min(x_in)
x_max = max(x_in)
x = [[] for _ in range(n_bins)]
for a in x_in:
# compute the bin number for value a
n = int(float(a - x_min) / (x_max - x_min + 1.0) * n_bins)
x[n].append(a)
return x # x is a binned list of elements from x_in
I've glossed over certain possible problems, like roundoff when defining the bin boundaries. But it will work with lists of any length, and the items in the list don't have to be integers.
Upvotes: 2