0

I have the following list of lists:

data = [[1,2,3],[4,5,6]]

and I want to generate something like the following:

[1,4]
[1,5]
[1,6]
[2,4]
[2,5]
[2,6]
[3,4]
[3,5]
[3,6]

What can produce the expected result? To clarify, I'm looking for all unique pairs of 1 item from each of the two sublists.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Rick
  • 43
  • 6

3 Answers3

2
import itertools
data = [[1,2,3],[4,5,6]]
print(list(itertools.product(*data)))

Output:

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
1

You can use itertools.product() with list unpacking to generate tuples containing one element from each sublist. You can then use map() to transform each of those tuples to lists.

from itertools import product
list(map(list, product(*data)))

This outputs:

[[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0
result = []
for x in data[0]:
    for y in data[1]:
        result.append([x, y])

or one line:

[(x,y) for x in data[0] for y in data[1]]

that will give you a list of tuples

list of lists:

list(map(list, [(x,y) for x in data[0] for y in data[1]]))
pzutils
  • 490
  • 5
  • 10