3 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
Itertools.groupby始終是答案!
在這里,我們將每個(gè)數(shù)字四舍五入到最接近的5,然后按相等的數(shù)字分組:
>>> 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貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果我們對(duì)正在使用的數(shù)字有所了解,我們可能會(huì)或多或少地節(jié)省時(shí)間。我們還可以想出一個(gè)非??焖俚姆椒ǎ膬?nèi)存效率非常低,但是如果適合您的目的,可以考慮一下:
#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貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
現(xiàn)在,我對(duì)您對(duì)組的定義有了更好的了解,我認(rèn)為這個(gè)相對(duì)簡(jiǎn)單的答案不僅會(huì)起作用,而且還應(yīng)該非??欤?/p>
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]
添加回答
舉報(bào)