H5W3
当前位置:H5W3 > 问答 > 正文

Get the cartesian product of a series of lists?

How can I get the Cartesian product (every possible combination of values) from a group of lists?

Input:

somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]

Desired output:

[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...]

Answer

itertools.product

Available from Python 2.6.

import itertools

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]
for element in itertools.product(*somelists):
    print(element)

Which is the same as,

for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
    print(element)

本文地址:H5W3 » Get the cartesian product of a series of lists?

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址