简体   繁体   English

在列表中查找所有可能的有序组

[英]Find all possible ordered groups in a list

Given an ordered list of integers: 给定一个有序的整数列表:

[1,3,7,8,9]

How can I find all the sublists that can be created from original list where order is maintained? 如何查找可以从维护订单的原始列表创建的所有子列表? Using the example above, I'm looking for a way to programmatically generate these sequences: 使用上面的示例,我正在寻找一种以编程方式生成这些序列的方法:

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

I'm basically looking for a way to generate all the permutations of a list where order is maintained. 我基本上正在寻找一种方法来生成维护订单的列表的所有排列。 I can generate all the sublists where there are only 2 sublists in total using this code: 我可以使用以下代码生成总共只有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]]

However, this code snippets only splits the original list in two and generates all the possible sublists where there are only two sublists. 但是,此代码片段仅将原始列表拆分为两个,并生成所有可能的子列表,其中只有两个子列表。 How can I generate all the possible sublists that can be created from original list where order is maintained? 如何生成可以从维护订单的原始列表创建的所有可能的子列表?

How about: 怎么样:

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

Result: 结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM