首先,定義你的“極”數
第二,根據這些“極”數生成間隔
第三,定義盡可能多的列表。在
然后,對于每個間隔,掃描列表并在相關列表中添加屬于該間隔的項
代碼: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]]