12

我在列表中有一个数字序列,我正在寻找一个优雅的解决方案,最好是列表理解,以获取单个序列(包括单个值)。我已经解决了这个小问题,但它不是很pythonic。

下面的列表定义了一个输入序列:

input = [1, 2, 3, 4, 8, 10, 11, 12, 17]

所需的输出应该是:

output = [
  [1, 2, 3, 4],
  [8],
  [10, 11, 12],
  [17],
]
4

2 回答 2

13
>>> from itertools import groupby, count
>>> nums = [1, 2, 3, 4, 8, 10, 11, 12, 17]
>>> [list(g) for k, g in groupby(nums, key=lambda n, c=count(): n - next(c))]
[[1, 2, 3, 4], [8], [10, 11, 12], [17]]
于 2013-05-01T08:46:02.197 回答
8

Pythonic 意味着简单、直接的代码,而不是单行代码。

def runs(seq):
    result = []
    for s in seq:
        if not result or s != result[-1][-1] + 1:
            # Start a new run if we can't continue the previous one.
            result.append([])
        result[-1].append(s)
    return result

print runs([1, 2, 3, 4, 8, 10, 11, 12, 17])
于 2013-05-01T09:08:42.013 回答