0

给定一个集合或一个列表(假设它是有序的)

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]
4

3 回答 3

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)
于 2013-06-08T02:31:27.480 回答
1

您想使用简单的除法和余数;该divmod()功能为您提供:

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
于 2013-06-08T01:37:17.060 回答
-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
于 2013-06-08T01:35:41.123 回答