简体   繁体   中英

Making a cartesian of tuples does not work

Have the following tuple:

t = (('x', (1, 2, 3), ('A', 'B')),
     ('y', (5, 6), ('E', 'G')))

How can the tuple be made to a cartesian as follows:

(('x', 1, 'A'),
 ('x', 1, 'B'),
 ('x', 2, 'A'),
 ...
 ('y', 6, 'G')

The following does not work:

from itertools import product
[(product(zip(a[0], a[1], a[2]))) for a in t]

No need to use zip , just unpack each tuple:

from itertools import product

data = (('x', (1, 2, 3), ('A', 'B')), ('y', (5, 6), ('E', 'G')))

result = [p for tup in data for p in product(*tup)]

for p in result:
    print(p)

Output

('x', 1, 'A')
('x', 1, 'B')
('x', 2, 'A')
('x', 2, 'B')
('x', 3, 'A')
('x', 3, 'B')
('y', 5, 'E')
('y', 5, 'G')
('y', 6, 'E')
('y', 6, 'G')

This is an extreme example of XY problem.

Why on Earth would you want that? I really think your real problem is something completely different, and strongly suggest you ask about what you really intend to do.

But just to satisfy the form, here is a way:

from itertools import chain, starmap, product
tuple(chain.from_iterable(starmap(product, t)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM