python中两个列表的置换映射

时间:2018-07-10 15:11:15

标签: python list dictionary permutation

如何在python中创建两个列表的排列映射?

例如,我有两个列表[1,2,3]['A','B','C']

然后我的代码应生成6个字典的列表

[ {1:'A',2:'B',3:'C'},
  {1:'A',2:'C',3:'B'},
  {1:'B',2:'A',3:'C'},
  {1:'B',2:'C',3:'A'},
  {1:'C',2:'A',3:'B'},
  {1:'C',2:'B',3:'A'} ]

2 个答案:

答案 0 :(得分:11)

在列表理解中使用zipitertools.permutations

>>> from itertools import permutations
>>> L1 = [1,2,3]
>>> L2 = ['A','B','C']
>>> [dict(zip(L1, p)) for p in permutations(L2)]
[{1: 'A', 2: 'B', 3: 'C'},
 {1: 'A', 2: 'C', 3: 'B'},
 {1: 'B', 2: 'A', 3: 'C'},
 {1: 'B', 2: 'C', 3: 'A'},
 {1: 'C', 2: 'A', 3: 'B'},
 {1: 'C', 2: 'B', 3: 'A'}]

答案 1 :(得分:2)

您似乎仅排列dict的值,因此您可以执行类似的操作

from itertools import permutations

dicts = []


keys = [1, 2, 3]
for values in permutations(['A', 'B', 'C']):
    new_dict = dict(zip(keys, values))
    dicts.append(new_dict)