1

I would to generate the Cartesian product of a list of tuples.

I am starting with a flat text file whose data looks like this:

1 1
0 1
2 2
3 3
0 5
3 4
5 6
0 -3
-2 -2

I then get it to a point where I have a list of tuples and the values are integers (converted from strings):

from csv import reader

f = reader(open('e:\\ucsd\\big_data_analytics\\programs\\week_1\\pa1\\data.txt', 'r'))
flat_list = [item for sublist in list(f) for item in sublist]
res = [tuple(map(int, sub.split(" "))) for sub in flat_list]
print(res)  # [(1, 1), (0, 1), (2, 2), (3, 3), (0, 5), (3, 4), (5, 6), (0, -3), (-2, -2)]

At this point I would the Cartesian product of the tuples in 'res'.

I've used Cartesian product in this way:

colors = ['black', 'white']
sizes = ['S', 'M', 'L']
shirts = [(color, size) for color in colors for size in sizes]
print(shirts)

I am not sure of how to get the Cartesian product of the list of tuples above.

It's the format that has me stumped.

MarkS
  • 1,455
  • 2
  • 21
  • 36
  • 1
    Have you tried itertools ? https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists – 7evy Aug 20 '21 at 19:05
  • Does this answer your question? [How to calculate a Cartesian product of a list with itself](https://stackoverflow.com/questions/41088160/how-to-calculate-a-cartesian-product-of-a-list-with-itself) – wjandrea Aug 21 '21 at 03:50

1 Answers1

1

This did the trick:

result = [(x, y) for x in res for y in res]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
MarkS
  • 1,455
  • 2
  • 21
  • 36