How can I match up permutations of a long list with a shorter list (according to the length of the shorter list)?

algorithm, combinatorics, list, python, python-itertools

Solution

Note: This answer is for the specific question asked above. If you are here from Google and just looking for a way to get a Cartesian product in Python, `itertools.product` or a simple list comprehension may be what you are looking for - see the other answers.

Suppose `len(list1) >= len(list2)`. Then what you appear to want is to take all permutations of length `len(list2)` from `list1` and match them with items from list2. In python:

import itertools
list1=['a','b','c']
list2=[1,2]

[list(zip(x,list2)) for x in itertools.permutations(list1,len(list2))]

Returns

[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]

Problem

I’m having trouble wrapping my head around a algorithm I’m try to implement. I have two lists and want to take particular combinations from the two lists. Here’s an example. ``` names = ['a', 'b'] numbers = [1, 2] ``` the output in this case would be: ``` [('a', 1), ('b', 2)] [('b', 1), ('a', 2)] ``` I might have more names than numbers, i.e. `len(names) >= len(numbers)`. Here's an example with 3 names and 2 numbers: ``` names = ['a', 'b', 'c'] numbers = [1, 2] ``` output: ``` [('a', 1), ('b', 2)] [('b', 1), ('a', 2)] [('a', 1), ('c', 2)] [('c', 1), ('a', 2)] [('b', 1), ('c', 2)] [('c', 1), ('b', 2)] ```

Original source

Related problems