[英]Generate all permutations of a list and permutations of the possible lists within that list?
說我有一個清單: [1,2,3]
我將如何生成:
[[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
我知道如何使用itertools.permutations(),但我不知道如何生成這部分[1],[2],[3],[1,2],[1,3],[2,3]
列表。
謝謝!
您的預期結果不包含所有可能的排列,因此不確定這是您想要的,或者您錯過了一些。 但要獲得不同長度列表的所有可能排列,您可以執行以下操作:
from itertools import permutations
a_list = [1,2,3]
perm_list = [p for l in range(1, len(a_list)+1) for p in permutations(a_list,l)]
print(perm_list)
結果是:
[(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
如果輸入列表很大,可能最好使用生成器表達式,例如
perm_list_gen = (p for l in range(1, len(a_list)+1) for p in permutations(a_list,l))
print(perm_list_gen)
#prints: <generator object <genexpr> at 0x7f176bbd88b8>
而不是一個一個地去,而不是一次一個:
for perm in perm_list_gen:
print(perm)
from itertools import permutations
lst = [1, 2, 3]
per = list(permutations(lst, 1)) + list(permutations(lst, 2)) + list(permutations(lst, 3))
輸出:
>>> [(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.