4

In python given an array like so:

a = [ 0, 1, 3, 4, 6, 7, 8, 10, 14 ]

I would like to split this into three uneven groups, such that I end up with something like this:

b = [0, 1, 3, 4]
c = [6, 7, 8]
d = [10, 14]

I want to group numbers by multiples of 5. So any integers from 0 - 4 would end up in the first array, 5 - 9 in the second, and so on.

4

3 回答 3

3

Itertools.groupby总是答案!

在这里,我们将每个数字向下舍入到最接近的 5,然后按相等的数字分组:

>>> for n, g in itertools.groupby(a, lambda x: round(x/5)*5):
    print list(g)

[0, 1, 3, 4]
[6, 7, 8]
[10, 14]
于 2013-06-01T03:34:11.913 回答
0

如果我们对正在处理的数字有所了解,我们可以或多或少地提高时间效率。我们还可以想出一个非常快速的内存效率非常低的内存,但是如果它符合您的目的,请考虑一下:

#something to store our new lists in
range = 5 #you said bounds of 5, right?
s = [ [] ]
for number in a:
    foundit = false
    for list in s:
        #deal with first number
        if len( list ) == 0:
            list.append( number )
        else:
            #if our number is within the same range as the other number, add it
            if list[0] / range == number / range:
                foundit = true
                list.append( number )
    if foundit == false:
       s.append( [ number ] )
于 2013-06-01T03:04:49.687 回答
0

现在我更好地理解了您对组的定义,我认为这个相对简单的答案不仅会起作用,而且应该非常快:

from collections import defaultdict

a = [0, 1, 3, 4, 6, 7, 8, 10, 14]
chunk_size = 5
buckets = defaultdict(list)

for n in a:
    buckets[n/chunk_size].append(n)

for bucket,values in sorted(buckets.iteritems()):
    print '{}: {}'.format(bucket, values)

输出:

0: [0, 1, 3, 4]
1: [6, 7, 8]
2: [10, 14]
于 2013-06-01T03:13:31.127 回答