给出一个有序的整数列表:
[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]]
但是,此代码段仅将原始列表拆分为两个,并生成所有可能的子列表,其中只有两个子列表。如何生成可以从维护订单的原始列表创建的所有可能的子列表?
答案 0 :(得分:8)
怎么样:
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]]