Skip to main content
 首页 » 编程设计

python之列表列表内和列表列表之间的排列[python]

2024年10月01日6www_RR

有很多相关的问题,但没有一个是我能找到的,完全符合我的要求。本质上,我想将每个子列表的所有排列放在一起以用于所有可能的组合,但将它们分开。因此:

input=[[1,2,3],[4],[5,6]] 

期望的输出:

[[1,2,3],[4],[6,5]] 
 
[[2,1,3],[4],[5,6]] 
 
[[2,1,3],[4],[5,6]] 
 
[[3,1,2],[4],[5,6]] 

等...

我相信下面的代码会起作用,但我想知道是否有更有效或更简洁的策略。非常感谢。

input=[[1,2,3],[4],[5,6]] 
all_lists=[] 
 
for i in xrange(len(input)): 
    all_lists.append(list(itertools.permutations(input[i]))) 
 
all_combinations = list(itertools.product(*all_lists)) 
 
## concat them together 
combinations_combined = [list(itertools.chain(*a)) for a in all_combinations] 

请您参考如下方法:

我们可以首先使用列表理解为每个子列表生成所有排列:

perms = [list(map(list,permutations(subl))) for subl in data] 

然后我们可以使用product获取产品。

for data in product(*perms): 
    print(list(data)) 

或完整:

from itertools import permutations, product 
 
def product_perms(data): 
    perms = [list(map(list,permutations(subl))) for subl in data] 
    for data in product(*perms): 
        print(list(data)) 

这会产生:

>>> product_perms(data) 
[[1, 2, 3], [4], [5, 6]] 
[[1, 2, 3], [4], [6, 5]] 
[[1, 3, 2], [4], [5, 6]] 
[[1, 3, 2], [4], [6, 5]] 
[[2, 1, 3], [4], [5, 6]] 
[[2, 1, 3], [4], [6, 5]] 
[[2, 3, 1], [4], [5, 6]] 
[[2, 3, 1], [4], [6, 5]] 
[[3, 1, 2], [4], [5, 6]] 
[[3, 1, 2], [4], [6, 5]] 
[[3, 2, 1], [4], [5, 6]] 
[[3, 2, 1], [4], [6, 5]] 

如果您想返回这样的列表,您可以使用:

def product_perms(data): 
    perms = [list(map(list,permutations(subl))) for subl in data] 
    return [list(data) for data in product(*perms)]