将范围内的整数列表分组为块

时间:2013-06-08 01:26:33

标签: python

给定一个集合或列表(假设其有序)

myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

我想知道一个范围内出现了多少个数字。 说我的范围是10.然后给出上面的列表,我有两组10。

我希望函数返回[10,10]

如果我的范围是15.那么我应该得到[15,5]

范围会发生变化。这就是我想出来的

myRange = 10
start = 1
current = start
next = current + myRange
count = 0
setTotal = []
for i in myset:
    if i >= current and i < next :
        count = count + 1
        print str(i)+" in "+str(len(setTotal)+1)
    else:
        current = current + myRange
        next = myRange + current
        if next >= myset[-1]:
            next = myset[-1]
        setTotal.append(count)
        count = 0

print setTotal

输出

1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 8]

通知11和20跳过了。我也玩了这个条件并得到了有线结果。

编辑:范围定义一个范围,该范围内的每个值都应计入一个夹头。

将范围从当前值到当前值+范围视为一个块。

编辑:

通缉输出:

1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 10]

3 个答案:

答案 0 :(得分:2)

使用正确的键功能,groupby模块中的itertools方法可以使此操作变得非常简单:

from itertools import groupby

def ranger(values, range_size):
    def keyfunc(n):
        key = n/(range_size+1) + 1
        print '{} in {}'.format(n, key)
        return key

    return [len(list(g)) for k, g in groupby(values, key=keyfunc)]

myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print ranger(myset, 10)
print ranger(myset, 15)

答案 1 :(得分:1)

你想使用简单的除法和余数; divmod() function给你们两个:

def chunks(lst, size):
    count, remainder = divmod(len(lst), size)
    return [size] * count + ([remainder] if remainder else [])

要创建所需的输出,请使用chunks()的输出:

lst = range(1, 21)
size = 10

start = 0
for count, chunk in enumerate(chunks(lst, size), 1):
    for i in lst[start:start + chunk]:
        print '{} in {}'.format(i, count)
    start += chunk

count是当前块的编号(从1开始; python通常使用基于0的索引)。

打印:

1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
20 in 2

答案 2 :(得分:-1)

如果您不关心给定块中的数字,您可以轻松计算尺寸:

def chunk_sizes(lst, size):
    complete = len(lst) // size  # Number of `size`-sized chunks
    partial = len(lst) % size    # Last chunk

    if partial:  # Sometimes the last chunk is empty
        return [size] * complete + [partial]
    else:
        return [size] * complete