4

所以我有一个索引列表,

[0, 1, 2, 3, 5, 7, 8, 10]

并想将其转换为此,

[[0, 3], [5], [7, 8], [10]]

这将在大量索引上运行。

此外,这在技术上不适用于 python 中的切片,我正在使用的工具在给定范围时比给定单个 id 时更快。

该模式基于在一个范围内,就像 python 中的切片一样。所以在示例中,1 和 2 被删除,因为它们已经包含在 0 到 3 的范围内。5 需要单独访问,因为它不在一个范围内,等等。这在大量 id 时更有帮助被包含在一个范围内,例如 [0, 5000]。

4

4 回答 4

6

Since you want the code to be fast, I wouldn't try to be too fancy. A straight-forward approach should perform quite well:

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]])

Admittedly, that's doesn't look too nice, but I expect the nicer solutions I can think of to perform worse. (I did not do a benchmark.)

Here is s slightly nicer, but slower solution:

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]])
于 2012-06-11T21:36:57.133 回答
3
def runs(seq):
    previous = None
    start = None
    for value in itertools.chain(seq, [None]):
        if start is None:
            start = value
        if previous is not None and value != previous + 1:
            if start == previous:
                yield [previous]
            else:
                yield [start, previous]
            start = value
        previous = value
于 2012-06-11T21:45:35.670 回答
1

由于性能是一个问题,请使用@SvenMarnach 的第一个解决方案,但这里有一个有趣的一条线,分成两行!:D

>>> from itertools import groupby, count
>>> indices = [0, 1, 2, 3, 5, 7, 8, 10]
>>> [[next(v)] + list(v)[-1:]
     for k,v in groupby(indices, lambda x,c=count(): x-next(c))]
[[0, 3], [5], [7, 8], [10]]
于 2012-06-12T06:35:33.180 回答
0

下面是一个简单的带有 numpy 的 python 代码:

def list_to_slices(inputlist):
      """
      Convert a flatten list to a list of slices:
      test = [0,2,3,4,5,6,12,99,100,101,102,13,14,18,19,20,25]
      list_to_slices(test)
      -> [(0, 0), (2, 6), (12, 14), (18, 20), (25, 25), (99, 102)]
      """
      inputlist.sort()
      pointers = numpy.where(numpy.diff(inputlist) > 1)[0]
      pointers = zip(numpy.r_[0, pointers+1], numpy.r_[pointers, len(inputlist)-1])
      slices = [(inputlist[i], inputlist[j]) for i, j in pointers]
      return slices
于 2017-03-16T13:35:47.223 回答