3 回答
TA贡献1796条经验 获得超7个赞
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]
TA贡献1836条经验 获得超4个赞
如果我们对正在使用的数字有所了解,我们可能会或多或少地节省时间。我们还可以想出一个非常快速的方法,它的内存效率非常低,但是如果适合您的目的,可以考虑一下:
#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 ] )
TA贡献1871条经验 获得超8个赞
现在,我对您对组的定义有了更好的了解,我认为这个相对简单的答案不仅会起作用,而且还应该非常快:
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]
添加回答
举报