簡體   English   中英

Python生成n個列表的所有n個排列

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM