我有一个数字列表,我想根据某个范围对它们进行分组。让我们说1000.我不想对每个连续的数字进行分组,而是将所有数字分组在1000范围内。
例如,
Data=[900,1050,1900,2100,9000,10000]
我需要的输出是:
[(900,1050,1900),(1900,2100),(9000,10000)]
答案 0 :(得分:1)
我不清楚你想如何处理边缘情况,但是你应该能够用一种相当天真的方法处理你想要的任何东西,例如
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]
答案 1 :(得分:0)
此代码查找所需的输出,并将每个范围作为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)