1

a python question here. I want to make a function to return a 2 dimensional list from a list of lists. I could not find this function in itertools.

Possibe inputs = list aa OR ab as shown below (different lengths)

aa = [[230, 115, 90, 264], [12, 9, 5], [-1], ['on', 'off']]
ab = [[230, 115, 90, 264], ['on', 'off']]

output for ab should be:

[[230, 'on'],
[230, 'off'],
[115, 'on'],
[115, 'off'],
[90, 'on'],
[90, 'off'],
[264, 'on'],
[264, 'off']]

output for aa should be:

[[230, 12, -1, 'on'],
[230, 12, -1, 'off'],
[230, 9, -1, 'on'],
[230, 9, -1, 'off'],
....
[264, 5, -1, 'off']]

1 Answers1

1

I think what you're asking for is the cartesian product of some iterables, for instance:

import itertools
import pprint

aa = [[230, 115, 90, 264], [12, 9, 5], [-1], ['on', 'off']]
ab = [[230, 115, 90, 264], ['on', 'off']]

for iterable in [aa, ab]:
    pprint.pprint(list(itertools.product(*aa)))

Result:

[(230, 12, -1, 'on'),
 (230, 12, -1, 'off'),
 (230, 9, -1, 'on'),
 (230, 9, -1, 'off'),
 (230, 5, -1, 'on'),
 (230, 5, -1, 'off'),
 (115, 12, -1, 'on'),
 (115, 12, -1, 'off'),
 (115, 9, -1, 'on'),
 (115, 9, -1, 'off'),
 (115, 5, -1, 'on'),
 (115, 5, -1, 'off'),
 (90, 12, -1, 'on'),
 (90, 12, -1, 'off'),
 (90, 9, -1, 'on'),
 (90, 9, -1, 'off'),
 (90, 5, -1, 'on'),
 (90, 5, -1, 'off'),
 (264, 12, -1, 'on'),
 (264, 12, -1, 'off'),
 (264, 9, -1, 'on'),
 (264, 9, -1, 'off'),
 (264, 5, -1, 'on'),
 (264, 5, -1, 'off')]
[(230, 12, -1, 'on'),
 (230, 12, -1, 'off'),
 (230, 9, -1, 'on'),
 (230, 9, -1, 'off'),
 (230, 5, -1, 'on'),
 (230, 5, -1, 'off'),
 (115, 12, -1, 'on'),
 (115, 12, -1, 'off'),
 (115, 9, -1, 'on'),
 (115, 9, -1, 'off'),
 (115, 5, -1, 'on'),
 (115, 5, -1, 'off'),
 (90, 12, -1, 'on'),
 (90, 12, -1, 'off'),
 (90, 9, -1, 'on'),
 (90, 9, -1, 'off'),
 (90, 5, -1, 'on'),
 (90, 5, -1, 'off'),
 (264, 12, -1, 'on'),
 (264, 12, -1, 'off'),
 (264, 9, -1, 'on'),
 (264, 9, -1, 'off'),
 (264, 5, -1, 'on'),
 (264, 5, -1, 'off')]
BPL
  • 9,632
  • 9
  • 59
  • 117