首页 > 解决方案 > 有没有办法在 Python3 中将列表分组为子列表?

问题描述

考虑以下:

some_list = [1, 2, 3, 4, 5, 9, 10]

如何通过不超过 1 的差异轻松地将这些整数分组?

final_list = [[1,2,3,4,5], [9, 10]]

我假设我需要使用 for 循环,并遍历原始列表,我只是有点不确定需要发生的逻辑。在此先感谢所有提供帮助的人!

final_list = []
group = []
init_position = some_list[0]
for i in some_list:
    if(i - init_position > 1):
        # re initialize group to empty here?
    else:
        group.append(i)
        init_position = i
     # Where do I append group to final_list now?
    



标签: python-3.xlist

解决方案


您可以只引用group[-1]而不是为列表中的最新项目保留变量。

def group_by_runs(sequence):
    # set up lists
    output = []
    group = []

    for elem in sequence:
        # if the group has any items in it,
        # and the last item is more than 1 removed from elem
        if group and elem - group[-1] > 1:
            # push the group to the output
            output.append(group)
            # reset the group
            group = []
        # add the next item to the group
        group.append(elem)

    # guard so we don't return an empty run
    if group:
        output.append(group)

    return output

推荐阅读