在lis中查找所有可能的有序组

2024-04-23 21:45:23 发布

您现在位置:Python中文网/ 问答频道 /正文

给定整数的有序列表:

[1,3,7,8,9]

如何从维护顺序的原始列表中找到可以创建的所有子列表?使用上面的示例,我正在寻找一种以编程方式生成这些序列的方法:

[[1],[3,7,8,9]]
[[1, 3],[7,8,9]]
[[1, 3, 7],[8,9]]
[[1, 3, 7, 8],[9]]
[[1, 3, 7, 8, 9]]
[[1, 3, 7], [8, 9]]
[[1], [3, 7], [8], [9]]
[[1], [3], [7, 8], [9]]
[[1], [3], [7], [8, 9]]
...

我基本上是在寻找一种方法来生成一个保持顺序的列表的所有排列。我可以使用以下代码生成总共只有2个子列表的所有子列表:

def partition(arr, idx):
    return [arr[:idx], arr[idx:]]

l = [1,3,7,8,9]
for idx in range(1, len(l)):
    groups = partition(l, idx)
    print(groups)

[[1], [3, 7, 8, 9]]
[[1, 3], [7, 8, 9]]
[[1, 3, 7], [8, 9]]
[[1, 3, 7, 8], [9]]

但是,此代码片段仅将原始列表一分为二,并在只有两个子列表的情况下生成所有可能的子列表。如何从维护顺序的原始列表生成所有可能的子列表?你知道吗


Tags: 方法示例列表顺序编程方式序列整数
1条回答
网友
1楼 · 发布于 2024-04-23 21:45:23

怎么样:

import itertools

def subsets(seq):
    for mask in itertools.product([False, True], repeat=len(seq)):
        yield [item for x, item in zip(mask, seq) if x]

def ordered_groups(seq):
    for indices in subsets(range(1, len(seq))):
        indices = [0] + indices + [len(seq)]
        yield [seq[a:b] for a,b in zip(indices, indices[1:])]

for group in ordered_groups([1,3,7,8,9]):
    print group

结果:

[[1, 3, 7, 8, 9]]
[[1, 3, 7, 8], [9]]
[[1, 3, 7], [8, 9]]
[[1, 3, 7], [8], [9]]
[[1, 3], [7, 8, 9]]
[[1, 3], [7, 8], [9]]
[[1, 3], [7], [8, 9]]
[[1, 3], [7], [8], [9]]
[[1], [3, 7, 8, 9]]
[[1], [3, 7, 8], [9]]
[[1], [3, 7], [8, 9]]
[[1], [3, 7], [8], [9]]
[[1], [3], [7, 8, 9]]
[[1], [3], [7, 8], [9]]
[[1], [3], [7], [8, 9]]
[[1], [3], [7], [8], [9]]

相关问题 更多 >