获取用零填充列表的所有排列

时间:2018-08-22 21:32:32

标签: python permutation

我有一个长度为ls的列表n,并希望以相同的顺序获取所有长度为m(其中m> n)的包含ls的列表,加(m-n)个零,插入到每个可能的位置组合。

例如:ls = [1, 2, 3]m = 4应该返回

[[1, 2, 3, 0],
 [1, 2, 0, 3],
 [1, 0, 2, 3],
 [0, 1, 2, 3]]

并且ls = [1, 2, 3]m = 5应该返回

[[1, 2, 3, 0, 0],
 [1, 2, 0, 3, 0],
 [1, 2, 0, 0, 3],
 [1, 0, 2, 3, 0],
 [1, 0, 2, 0, 3],
 [1, 0, 0, 2, 3],
 [0, 1, 2, 3, 0],
 [0, 1, 2, 0, 3],
 [0, 1, 0, 2, 3],
 [0, 0, 1, 2, 3]]

该解决方案应快速且内存有效-特别是应避免生成重复的解决方案。任何帮助表示赞赏!

尝试(但效率低下)的尝试:

ls = [1, 2, 3]
m = 4

from itertools import permutations

n = len(ls)
results = []
for t in set(permutations('1' * n + '0' * (m - n))):
    idxs = [i for i, j in enumerate(t) if j == '1']
    result = [0] * m
    for idx, value in zip(idxs, ls):
        result[idx] = value
    results.append(result)

1 个答案:

答案 0 :(得分:1)

使用itertools.combinations生成插入零的所有位置组合。然后使用列表推导选择0或下一个原始元素来构建新列表。

# Pad list orig with zeroes, out to "m" total elements.
from itertools import combinations

orig = [1, 2, 3]
m = 5
n = len(orig)

padded = []

for pad_idx in combinations(range(m), m-n):
    t = orig[:]
    padded.append( [0 if i in pad_idx else t.pop(0)
                    for i in range(m)] )

print(padded)

输出(为便于阅读而格式化):

[[0, 0, 1, 2, 3], 
 [0, 1, 0, 2, 3], 
 [0, 1, 2, 0, 3], 
 [0, 1, 2, 3, 0], 
 [1, 0, 0, 2, 3], 
 [1, 0, 2, 0, 3], 
 [1, 0, 2, 3, 0], 
 [1, 2, 0, 0, 3], 
 [1, 2, 0, 3, 0], 
 [1, 2, 3, 0, 0]]