[英]generate all k-Permutations from n+1 without recalculate the k-permutations from n python 3
[英]Python generate all n-permutations of n lists
我有n個不同長度的列表,我想創建所有可能的排列。
所以,例如,如果a=[1,2]
和b=[3,4,5]
那么我希望得到res=[[1,3],[1,4],[1,5],[2,3],[2,4],[2,5]]
我一直在嘗試使用遞歸函數實現這一點,結果證明既不是非常有效也不是非常pythonic。 經驗豐富的python程序員將如何解決這個問題?
它被稱為兩個序列的笛卡爾積 。
這已經在Python中作為庫函數提供: itertools.product
。
例:
>>> import itertools
>>> a = [1, 2]
>>> b = [3, 4, 5]
>>> list(itertools.product(a, b))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
你可以通過itertools中的產品功能來做到這一點,
import itertools
a = [1,2]
b = [3, 4, 5]
out = list(itertools.product(a,b))
print out
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
itertools肯定是要走的路,但如果你不想走簡單的路線......
def print_permutations(lists, perms=[]):
if not lists:
print perms
else:
current_layer = lists[0]
remaining_layers = lists[1:]
for word in current_layer:
print_permutations(remaining_layers, perms + [word])
l = (('quick', 'lazy'), ('brown', 'black', 'grey'), ('fox', 'dog'))
print_permutations(l)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.