我有以下函式來獲取串列的排列數(沒有重復元素):
import itertools
def permutations_without_repetition(samples, size):
return list(itertools.permutations(samples, size))
只要我提供的串列不包含嵌套串列,這對我來說就很好用。Itertools 將嵌套元素視為一個完整的元素,并且不會打擾生成包含不同順序嵌套串列的排列。
如果我運行permutations_without_repetition([[1, 2], 3], 2),我得到的唯一結果是:
[([1, 2], 3), (3, [1, 2])]
我知道這是預期的行為,但我希望結果是:
[([1, 2], 3), (3, [1, 2]), ([2, 1], 3), (3, [2, 1])]
回傳包含嵌套串列排列的排列以產生上述結果的最簡單方法是什么?
uj5u.com熱心網友回復:
您可以使用遞回生成器函式:
def combos(d, c = []):
if not isinstance(d, list):
yield d
elif not d:
yield c
else:
for i, a in enumerate(d):
for k in combos(a, c = []):
yield from combos(d[:i] d[i 1:], c [k])
print(list(combos([[1, 2], 3])))
輸出:
[[[1, 2], 3], [[2, 1], 3], [3, [1, 2]], [3, [2, 1]]]
使用更短的解決方案itertools:
import itertools as it
def combos(d):
if not isinstance(d, list):
yield d
else:
for i in it.permutations(d):
yield from map(list, it.product(*[combos(j) for j in i]))
print(list(combos([[1, 2], 3])))
輸出:
[[[1, 2], 3], [[2, 1], 3], [3, [1, 2]], [3, [2, 1]]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/335378.html
