'python how to find unique pairs from 2 lists [duplicate]
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.
Solution 1:[1]
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)]
Solution 2:[2]
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]]
Solution 3:[3]
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]]))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
| Solution 2 | BrokenBenchmark |
| Solution 3 | pzutils |
