首页 > 解决方案 > Python all combinations of one item per list

问题描述

I have a varying number of lists of varying length. I need to try to create all possibilities of having one item per list. How can this be done in Python?

Example

l1 =  ['a', 'b', 'c']
l2 =  [1, 2]
l3 =  [6]

# Expected result:
[
  ['a', 1, 6],
  ['a', 2, 6],
  ['b', 1, 6],
  ['b', 2, 6],
  ['c', 1, 6],
  ['c', 2, 6],
]

I could have 3 loops in this case, but since this is for an ambiguous number of lists it doesn't scale.

I tried playing with itertools a bit but couldn't figure out what to use for my case and couldn't find similar questions here. So any help would be appreciated.

标签: pythonloopsitertoolscombinatorics

解决方案


If you have a varying number of lists, you should use a list of lists, not separate variables. Then you can spread the list into arguments to itertools.product().

import itertools

lists = [
    ['a', 'b', 'c'],
    [1, 2],
    [6]
]

print(list(itertools.product(*lists)))

推荐阅读