6

我有以下问题。有一个整数列表,我想将它拆分为一个列表列表,只要原始输入列表的两个元素之间的步长不是 1。例如:input = [0, 1, 3, 5, 6, 7 ], 输出 = [[0, 1], [3], [5, 6, 7]]

我编写了以下函数,但它非常丑陋,我想知道你们中的任何人是否会帮助我获得更好的解决方案。我尝试使用 itertools,但无法解决。

这是我的解决方案:

def _get_parts(list_of_indices):
    lv = list_of_indices
    tuples = zip(lv[:-1], lv[1:])
    split_values = []
    for i in tuples:
        if i[1] - i[0] != 1:
            split_values.append(i[1])
    string = '/'.join([str(i) for i in lv])
    substrings = []
    for i in split_values:
        part = string.split(str(i))
        substrings.append(part[0])
        string = string.lstrip(part[0])
    substrings.append(string)
    result = []
    for i in substrings:
        i = i.rstrip('/')
        result.append([int(n) for n in i.split('/')])
    return result

非常感谢!

4

5 回答 5

8

这适用于任何可迭代的

>>> from itertools import groupby, count
>>> inp = [0, 1, 3, 5, 6, 7]
>>> [list(g) for k, g in groupby(inp, key=lambda i,j=count(): i-next(j))]
[[0, 1], [3], [5, 6, 7]]
于 2013-02-22T08:40:35.000 回答
2
def _get_parts(i, step=1):
    o = []
    for x in i:
        if o and o[-1] and x - step == o[-1][-1]:
            o[-1].append(x)
        else:
            o.append([x])
    return o

_get_parts([0, 1, 3, 5, 6, 7], step=1)
# [[0, 1], [3], [5, 6, 7]])
于 2013-02-22T08:38:18.727 回答
0

这是一个利用 for 循环的解决方案。

def splitbystep(alist):
  newlist = [[alist[0]]]
  for i in range(1,len(alist)):
    if alist[i] - alist[i-1] == 1:
      newlist[-1].append(alist[i])
    else:
      newlist.append([alist[i]])
  return newlist
于 2013-02-22T08:42:59.687 回答
0

这就是我的做法:

inp = [0, 1, 3, 5, 6, 7]
base = []

for item in inp:
    if not base or item - base[-1][-1] != 1: # If base is empty (first item) or diff isn't 1
        base.append([item])                  # Append a new list containing just one item
    else:
        base[-1].append(item)                # Otherwise, add current item to the last stored list in base
print base                                   # => [[0, 1], [3], [5, 6, 7]]
于 2013-02-22T08:44:31.193 回答
0

这是模块more_itertools中函数split_when的教科书用例:

import more_itertools

print(list(more_itertools.split_when([0, 1, 3, 5, 6, 7], lambda x,y: y-x != 1)))
# [[0, 1], [3], [5, 6, 7]]

或者,更简单的是more_itertools.consecutive_groups

print([list(g) for g in more_itertools.consecutive_groups([0, 1, 3, 5, 6, 7])])
# [[0, 1], [3], [5, 6, 7]]
于 2021-09-16T10:07:50.273 回答