根据序列中缺失的数字拆分列表
我正在寻找最Pythonic的方法,根据序列中缺少的数字将数字列表拆分为更小的列表。例如,如果初始列表是:
seq1 = [1, 2, 3, 4, 6, 7, 8, 9, 10]
该函数将产生:
[[1, 2, 3, 4], [6, 7, 8, 9, 10]]
或
seq2 = [1, 2, 4, 5, 6, 8, 9, 10]
将导致:
[[1, 2], [4, 5, 6], [8, 9, 10]]
I am looking for the most pythonic way of splitting a list of numbers into smaller lists based on a number missing in the sequence. For example, if the initial list was:
seq1 = [1, 2, 3, 4, 6, 7, 8, 9, 10]
the function would yield:
[[1, 2, 3, 4], [6, 7, 8, 9, 10]]
or
seq2 = [1, 2, 4, 5, 6, 8, 9, 10]
would result in:
[[1, 2], [4, 5, 6], [8, 9, 10]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
旧 Python 文档 中的 Python 3 版本代码:
groupby
来自 itertools 模块的函数生成一个每次关键函数更改其返回值时都会中断。技巧在于返回值是列表中的数字减去列表中元素的位置。当数字存在差距时,这种差异就会发生变化。itemgetter
函数来自 operator 模块 ,您必须导入它和 itertools 模块才能使该示例正常工作。或者,作为列表理解:
Python 3 version of the code from the old Python documentation:
The
groupby
function from the itertools module generates a break every time the key function changes its return value. The trick is that the return value is the number in the list minus the position of the element in the list. This difference changes when there is a gap in the numbers.The
itemgetter
function is from the operator module, you'll have to import this and the itertools module for this example to work.Alternatively, as a list comprehension:
这是一个适用于 Python 3 的解决方案(基于之前仅适用于 python 2 的答案)。
或作为列表理解
需要进行更改,因为
This is a solution that works in Python 3 (based on previous answers that work in python 2 only).
or as a list comprehension
Changes were needed because
另一个不需要 itertools 等的选项:
Another option which doesn't need itertools etc.:
我的方式
结果
My way
Result
我更喜欢这个,因为它不需要任何额外的库或对第一种情况进行特殊处理:
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 15, 16, 17, 18, 20, 21, 22]
[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12], [15, 16, 17, 18], [20, 21, 22]]
I like this one better because it doesn't require any extra libraries or special treatment for first case:
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 15, 16, 17, 18, 20, 21, 22]
[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12], [15, 16, 17, 18], [20, 21, 22]]
使用 numpy 的简短单行:
结果:
Short one-liner using numpy:
Result: