首页 > 解决方案 > 创建特定排列 Python

问题描述

我有一个二维列表的值:

# 4 x 4, 2-dimensional list
values = [[4, 7, 8], 
          [1, 3, 4], 
          [7, 5, 6], 
          [2, 9, 1]]

我想为每个列表创建包含这些值(笛卡尔积)的所有可能排列的元组。

# example for the list at index 0 of values
args0 = [(4, 7, 8), (7, 4, 8), (4, 8, 7), (8, 4, 7), (7, 8, 4), (8, 7, 4)] 

有没有简单的方法来解决这个问题?我已经尝试过 itertools 但无法让它与“特定值”一起使用。

标签: pythonlistpermutationitertools

解决方案


您想要的是列表中每个元素的排列,所以只需map itertools.permutations

import itertools

values = [[4, 7, 8], 
          [1, 3, 4], 
          [7, 5, 6], 
          [2, 9, 1]]

perms = map(itertools.permutations, values)
for v in perms:
    print(list(v)) 

结果:

[(4, 7, 8), (4, 8, 7), (7, 4, 8), (7, 8, 4), (8, 4, 7), (8, 7, 4)]
[(1, 3, 4), (1, 4, 3), (3, 1, 4), (3, 4, 1), (4, 1, 3), (4, 3, 1)]
[(7, 5, 6), (7, 6, 5), (5, 7, 6), (5, 6, 7), (6, 7, 5), (6, 5, 7)]
[(2, 9, 1), (2, 1, 9), (9, 2, 1), (9, 1, 2), (1, 2, 9), (1, 9, 2)]

这里有一个活生生的例子


推荐阅读