python数列分段_按范围分段的Python数组
首先,定義你的“極”數(shù)
第二,根據(jù)這些“極”數(shù)生成間隔
第三,定義盡可能多的列表。在
然后,對(duì)于每個(gè)間隔,掃描列表并在相關(guān)列表中添加屬于該間隔的項(xiàng)
代碼: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)
結(jié)果:
^{pr2}$
此解決方案的優(yōu)點(diǎn)是通過(guò)添加更多的“極”數(shù)來(lái)適應(yīng)3個(gè)以上的列表/間隔。在
編輯:如果輸出列表順序無(wú)關(guān)緊要,有一個(gè)很好的快速解決方案(O(log(N)*N)):首先對(duì)輸入列表進(jìn)行排序
然后使用bisect生成切片子列表,它返回所提供數(shù)字的插入位置(左&右)
像這樣: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)
結(jié)果:[[1, 2], [4, 5], [7, 8, 9, 10]]
總結(jié)
以上是生活随笔為你收集整理的python数列分段_按范围分段的Python数组的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: “犬马恋主情”上一句是什么
- 下一篇: python字符串转date,在Pyth