我在列表中有一系列数字,我正在寻找一个优雅的解决方案,最好是列表理解,以获得单个序列(包括单个值)。我已经解决了这个小问题,但它并不是非常pythonic。
以下列表定义了输入序列:
input = [1, 2, 3, 4, 8, 10, 11, 12, 17]
所需的输出应为:
output = [
[1, 2, 3, 4],
[8],
[10, 11, 12],
[17],
]
答案 0 :(得分: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]]
答案 1 :(得分: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])