提前感谢任何建议! 我有一组随机的数字需要根据他们的范围分组...我可以使用一些建议如何做到这一点...提前感谢
所以,我想这段代码是这样的: 列出100个随机数,范围从0到1000 将范围(从0-1000)拆分为x个组(比如10组:0-100,100-200,200-300等...) 对于我在这个列表中 测试它是否在第1组中 如果为true,则将其添加到列表中 如果不测试连续组
问题是组的数量应该是一个可以调整的变量,后续的列表应该根据范围的划分进行更新......
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
而不是实际的数字
谢谢!!! - E答案 0 :(得分:0)
解决此类问题的常用方法是编写一个完成工作的函数,并使用不同的输入参数调用该函数。像这样:
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
我已经掩盖了某些可能的问题,例如在定义bin边界时的舍入。但它适用于任何长度的列表,列表中的项目不必是整数。