在python中,给出如下数组:
a = [ 0, 1, 3, 4, 6, 7, 8, 10, 14 ]我想把它分成三个不均匀的组,这样我就会得到这样的结果:
b = [0, 1, 3, 4]
c = [6, 7, 8]
d = [10, 14]我想用5的倍数对数字进行分组,所以从0到4的任何整数都会在第一个数组中结束,5-9在第二个数组中结束,依此类推。
发布于 2013-06-01 11:34:12
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-01 11:04:50
如果我们对正在处理的数字有所了解,我们可以或多或少地提高时间效率。我们也可以想出一个内存效率极低的非常快速的方法,但如果它适合您的目的,请考虑以下内容:
#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-01 11:13:31
现在我更好地理解了你对组的定义,我认为这个相对简单的答案不仅有效,而且应该非常快:
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]https://stackoverflow.com/questions/16868377
复制相似问题