[英]Permutations of list of lists
假設有一個元素列表列表。 每個列表中可以包含任何元素。 例如[[1,2,3,4],[2,3],[4,5,6,7],[1]]
。 我試圖生成這樣的列表的排列,我應該在一個這樣的排列中從最里面的列表中只選擇一個。 所以輸出將是[1,2,4,1],[1,3,4,1] ......
樣本輸入= [[1,2],[3],[4]]
樣本輸出= [[1,3,4],[2,3,4]]
我之前嘗試過一些具有錯誤邏輯的代碼。 以下是我處於中途並陷入困境的代碼。 我無法接受它。 我不擅長排列和組合。
我正在嘗試的是與上面描述的相同,只是以下是坐標集。 i,最里面的元素(在輸入中)是坐標集。
[[[1,2],[2,4]],[[2,3],[4,2]],[[1,5]],[[3,3],[7,2],[5,6]]]
def perm(a,length):
arr=[]
k=0
while (k<length):
temp=[]
for i in a:
a=[[[1,2],[2,4]],[[2,3],[4,2]],[[1,5]],[[3,3],[7,2],[5,6]]]
perm(a)
如需進一步說明,請與我們聯系。 任何幫助表示贊賞。
編輯
我想要一個不使用itertools或任何這樣的python模塊的解決方案。 我以前應該提到它。 否則它是一個有效且非常方便的解決方案。
Psuedo代碼用於回答的邏輯或用方法而不是使用python庫的簡單答案。 很抱歉很晚才添加這個細節。
您可以使用itertools.product
輕松完成此操作:
>>> from itertools import product
>>> list(product(*[[1,2],[3],[4]]))
[(1, 3, 4), (2, 3, 4)]
>>> list(product(*[[1,2,3,4],[2,3],[4,5,6,7],[1]]))
[(1, 2, 4, 1), (1, 2, 5, 1), (1, 2, 6, 1), (1, 2, 7, 1),
(1, 3, 4, 1), (1, 3, 5, 1), (1, 3, 6, 1), (1, 3, 7, 1),
(2, 2, 4, 1), (2, 2, 5, 1), (2, 2, 6, 1), (2, 2, 7, 1),
(2, 3, 4, 1), (2, 3, 5, 1), (2, 3, 6, 1), (2, 3, 7, 1),
(3, 2, 4, 1), (3, 2, 5, 1), (3, 2, 6, 1), (3, 2, 7, 1),
(3, 3, 4, 1), (3, 3, 5, 1), (3, 3, 6, 1), (3, 3, 7, 1),
(4, 2, 4, 1), (4, 2, 5, 1), (4, 2, 6, 1), (4, 2, 7, 1),
(4, 3, 4, 1), (4, 3, 5, 1), (4, 3, 6, 1), (4, 3, 7, 1)]
根據文檔,幾乎沒有任何import
的等效實現:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
我發現以下遞歸版本比使用列表理解的版本更具可讀性,但我想這是一個品味問題:
def cartesianProduct( *lists ) :
if not lists : # nothing to do, yield empty tuple
yield ()
else : # let's do A x cartesianProduct( B x C x ... )
for a in lists[0] : # each element of A
for tup in cartesianProduct( *lists[1:] ) : # each tuple of ( B x C x ... )
yield ( a, ) + tup # concatenate and yield
list( product( 'AB', range(3), 'xy' ) ) == list( cartesianProduct('AB', range(3), 'xy') )
True
你可以使用numpy
來排列列表! 這段代碼: numpy.permutation(arr)
所以如果你想為嵌套列表做到這一點,你可以用一個循環做到這一點,如for
!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.