简体   繁体   English

如何使用python中的某个范围对数字列表进行分组?

[英]How do I group list of numbers using some range in python?

I have a list of numbers and I want to group them based on some range.我有一个数字列表,我想根据某个范围对它们进行分组。 Let's say 1000. Instead of grouping every consecutive number, I want to group all numbers that are within range of 1000 of one another.比方说 1000。我不想将每个连续的数字分组,而是将所有在 1000 范围内的数字分组。

For example,例如,

Data=[900,1050,1900,2100,9000,10000]

The output which I require is:我需要的输出是:

[(900,1050,1900),(1900,2100),(9000,10000)]

It's not completely clear to me how you want to handle the edge cases, but you should be able to handle whatever you want with a fairly naive approach, such as我并不完全清楚您想如何处理边缘情况,但是您应该能够以一种相当天真的方法处理您想要的任何事情,例如

def group(l, group_range):
    groups = []
    this_group = []
    i = 0
    while i < len(l):
        a = l[i]
        if len(this_group) == 0:
            if i == len(l) - 1:
                break
            this_group_start = a
        if a <= this_group_start + group_range:
            this_group.append(a)
        if a < this_group_start + group_range:
            i += 1
        else:
            groups.append(this_group)
            this_group = []
    groups.append(this_group)
    return [tuple(g) for g in groups if len(g) != 0]

This code finds the required output and returns each range as an entry into a Python list.此代码查找所需的输出并将每个范围作为 Python 列表的条目返回。

import numpy

data=numpy.array([-5600, 900,2400,1050,1900,2100,9000,10000])
data_max = numpy.max(data)
data_min = numpy.min(data)

num_thousands = numpy.floor(data_min/1000)
start_value  = num_thousands*1000

num_thousands = numpy.floor(data_max/1000)
end_value  = num_thousands*1000
num_thousands = (end_value - start_value)/1000
msg = ''
loop_range_start = start_value
loop_range_end = start_value + 1000

num = 0

a = []
for k in numpy.arange(num_thousands):
    if(k==num_thousands-1):
        temp = numpy.logical_and(data>=loop_range_start, data<=loop_range_end)
    else:
        temp = numpy.logical_and(data>=loop_range_start, data<loop_range_end)
    vals = data[temp]
    if(vals.shape[0] != 0):
        vals = numpy.sort(vals)
        a.append(vals.tolist())
        num = num + 1
    loop_range_start = loop_range_start + 1000
    loop_range_end = loop_range_end + 1000

print('There are ', num, ' ranges.')
print(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM