首先,定义你的“极”数
第二,根据这些“极”数生成间隔
第三,定义尽可能多的列表。在
然后,对于每个间隔,扫描列表并在相关列表中添加属于该间隔的项
代码:source = [1, 4, 7, 9, 2, 10, 5, 8]
poles = (0,3,6,25)
intervals = [(poles[i],poles[i+1]) for i in range(len(poles)-1)]
# will generate: intervals = [(0,3),(3,6),(6,25)]
output = [list() for _ in range(len(intervals))]
for out,(start,stop) in zip(output,intervals):
for s in source:
if start <= s
out.append(s)
print(output)
结果:
^{pr2}$
此解决方案的优点是通过添加更多的“极”数来适应3个以上的列表/间隔。在
编辑:如果输出列表顺序无关紧要,有一个很好的快速解决方案(O(log(N)*N)):首先对输入列表进行排序
然后使用bisect生成切片子列表,它返回所提供数字的插入位置(左&右)
像这样:import bisect
source = sorted([1, 4, 7, 9, 2, 10, 5, 8])
poles = (0,3,6,25)
output = [source[bisect.bisect_left(source,poles[i]):bisect.bisect_right(source,poles[i+1])] for i in range(len(poles)-1)]
print(output)
结果:[[1, 2], [4, 5], [7, 8, 9, 10]]