Python-使用列表理解来查找递增编号的序列 [英] Python - find incremental numbered sequences with a list comprehension
本文介绍了Python-使用列表理解来查找递增编号的序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在列表中有一个数字序列,我在寻找一种优雅的解决方案,最好是列表理解,以获得单个序列(包括单个值).我已经解决了这个小问题,但是它不是pythonic.
I have a sequence of numbers in a list and I'm looking for an elegant solution, preferably list comprehension, to get the individual sequences (including single values). I have solved this small problem but it is not very pythonic.
以下列表定义了输入序列:
The following list defines an input sequence:
input = [1, 2, 3, 4, 8, 10, 11, 12, 17]
所需的输出应为:
output = [
[1, 2, 3, 4],
[8],
[10, 11, 12],
[17],
]
推荐答案
>>> 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]]
这篇关于Python-使用列表理解来查找递增编号的序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文