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]
如果我们对正在使用的数字有所了解,我们可能会或多或少地节省时间。我们还可以想出一个非常快速的方法,它的内存效率非常低,但是如果适合您的目的,可以考虑一下:#something to store our new lists inrange = 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 ] )