Permutation mapping of two lists in python

  • A+
Category:Languages

How can I create a permutation mapping of two lists in python?

For example I have two lists [1,2,3] and ['A','B','C']

Then my code should generate a list of 6 dictionaries

[ {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'} ] 

 


Using zip and itertools.permutations in a list comprehension:

>>> 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'}] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: