python - 将列表作为嵌套列表,在单独列表中包含连续元素

标签 python

我想将元素列表分成嵌套列表,每个子列表都有连续的元素。如果一个元素没有连续的元素,它应该在单个列表中。

输入:

l1 = [1, 2, 3, 11, 12, 13, 23, 33, 34, 35, 45]
l2 = [11, 12, 13, 22, 23, 24, 33, 34]
l3 = [1, 2, 3, 11, 12, 13, 32, 33, 34, 45]

预期输出:

l1 = [[1, 2, 3], [11, 12, 13], [23], [33, 34, 35], [45]]
l2 = [[11, 12, 13], [22, 23, 24], [33, 34]]
l3 = [[1, 2, 3], [11, 12, 13], [32, 33, 34], [45]]

我已经尝试了下面的代码,但它没有给出预期的结果,打印了一个空列表:

def split_into_list(l):

    t = []
    for i in range(len(l) - 1):

        if abs(l[i] - l[i + 1]) == 0:
            t.append(l[i])

        elif abs(l[i] - l[i + 1]) != 0 and abs(l[i - 1] - l[i]) == 0:
            t.append(l[i])
            yield t
            split_into_list(l[i:])
        if i + 1 == len(l):
            t.append(l[i])
            yield t

l = [1, 2, 3, 11, 12, 13, 32, 33, 34, 45]
li = []
li.append(split_into_list(l))

for i in li:
    print(i, list(i))

最佳答案

使用自定义 split_adjacent 函数的更短方法:

def split_adjacent(lst):
    res = [[lst[0]]]    # start/init with the 1st item/number
    for i in range(1, len(lst)):
        if lst[i] - res[-1][-1] > 1:  # compare current and previous item
            res.append([])
        res[-1].append(lst[i])
    return res


l1 = [1, 2, 3, 11, 12, 13, 23, 33, 34, 35, 45]
l2 = [11, 12, 13, 22, 23, 24, 33, 34]
l3 = [1, 2, 3, 11, 12, 13, 32, 33, 34, 45]

print(split_adjacent(l1))
print(split_adjacent(l2))
print(split_adjacent(l3))

最终输出:

[[1, 2, 3], [11, 12, 13], [23], [33, 34, 35], [45]]
[[11, 12, 13], [22, 23, 24], [33, 34]]
[[1, 2, 3], [11, 12, 13], [32, 33, 34], [45]]

关于python - 将列表作为嵌套列表,在单独列表中包含连续元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58432920/

相关文章:

python - 如何使用 doctest 检查程序是否产生了某些输出?

python - 如何在python中使变量不可变

python - 无法挖掘链接按钮下的某些信息

具有 defaultdict(int) 行为的 Python 计数器

python - django rest 框架权限 'isAdminorReadonly'

Python - 新手 : Why this simple if-elif (replication of the C case block) always produces the same result?

python - PyTorch - 自定义 ReLU 平方实现

python - 立即检查一组变量的 boolean 值

python - 从文件中读取会删除文档中最后一个字符串的最后一个字母?

python - 有没有办法以编程方式删除 Azure 中的 SQL 数据库?