Python:基于它们之间的步骤拆分整数列表 [英] Python: split list of integers based on step between them

查看:127
本文介绍了Python:基于它们之间的步骤拆分整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following problem. Having a list of integers, I want to split it, into a list of lists, whenever the step between two elements of the original input list is not 1. For example: input = [0, 1, 3, 5, 6, 7], output = [[0, 1], [3], [5, 6, 7]]

我写了以下函数,但它是我真是天哪,我想知道你们中的任何人是否会帮助我找到更好的解决方案。我试图使用itertools,但无法解决它。

I wrote the following function, but it's uggly as hell, and I was wondering if anyone of you guys would help me get a nicer solution. I tried to use itertools, but couldn't solve it.

这是我的解决方案:

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

非常感谢!

推荐答案

这适用于任何可迭代的

>>> 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]]

这篇关于Python:基于它们之间的步骤拆分整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆