Sae*_*bin 4 python list range slice
所以我有一个索引列表,
[0, 1, 2, 3, 5, 7, 8, 10]
Run Code Online (Sandbox Code Playgroud)
并希望将其转换为此,
[[0, 3], [5], [7, 8], [10]]
Run Code Online (Sandbox Code Playgroud)
这将在大量指数上运行.
此外,这在技术上不适用于python中的切片,与给定单个ID相比,我使用的工具在给定范围时更快.
该模式基于在一个范围内,就像切片在python中工作一样.因此在示例中,1和2被删除,因为它们已经包含在0到3的范围内.5需要单独访问,因为它不在范围内等等.当大量id时,这更有用包含在[0,5000]等范围内.
既然你想要快速的代码,我不会试图太花哨.一个直截了当的方法应该表现得很好:
a = [0, 1, 2, 3, 5, 7, 8, 10]
it = iter(a)
start = next(it)
slices = []
for i, x in enumerate(it):
if x - a[i] != 1:
end = a[i]
if start == end:
slices.append([start])
else:
slices.append([start, end])
start = x
if a[-1] == start:
slices.append([start])
else:
slices.append([start, a[-1]])
Run Code Online (Sandbox Code Playgroud)
不可否认,这看起来并不太好,但我希望我能想到的更好的解决方案表现得更差.(我没有做基准测试.)
这是一个更好,但更慢的解决方案:
from itertools import groupby
a = [0, 1, 2, 3, 5, 7, 8, 10]
slices = []
for key, it in groupby(enumerate(a), lambda x: x[1] - x[0]):
indices = [y for x, y in it]
if len(indices) == 1:
slices.append([indices[0]])
else:
slices.append([indices[0], indices[-1]])
Run Code Online (Sandbox Code Playgroud)