python - 根据范围对随机数字列表进行分组

标签 python list sorting

预先感谢您的任何建议! 我有一组随机数字,需要根据它们的范围进行分组...我可以使用一些建议如何做到这一点...提前致谢

所以,我想代码是这样工作的: 获取 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

最佳答案

解决此类问题的通常方法是编写一个执行该工作的函数,并使用不同的输入参数调用该函数。像这样:

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 边界时的舍入。但它适用于任何长度的列表,并且列表中的项目不必是整数。

关于python - 根据范围对随机数字列表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48712803/

相关文章:

python - PIP 随机失败 'Could not find a version that satisfies the requirement' 相同要求.txt

python - 如何在 Python Webdriver 中运行 1 个以上的测试用例。我的测试用例类中只有 1 个运行

python - 嵌套结构 : List of lists of tuples python

javascript - 对列表元素进行排序node.js

python - 如何按列对多维数组进行排序?

python - Selenium 的应用程序没有响应 - 不显示进度条,并且在任务完成之前不在控制台中发出文本

python - .sav 文件无效签名异常

list - 删除重复的解决方案

android - 简单的待办事项列表示例在 Android 上不起作用

c++ - boost 绑定(bind)到 operator[]