Duke
Duke

Reputation: 368

recursively create tuples from lists

I have a list of lists such as:
[[1,2,3],[4,5,6],[7,8,9]] I'm trying to create tuples of the form (1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(2,4),(2,5),(4,7),(4,8),...

In other words, items in the first list should be tuples with items in subsequent lists, items in the second list, tuples with items from its subsequent lists and so on, until we get to the last list.

I'm a bit unsure of how a list comprehension in python here would work. Any ideas?

Thanks.

Upvotes: 2

Views: 1727

Answers (4)

Karl Knechtel
Karl Knechtel

Reputation: 61616

Without destroying the original list:

from itertools import chain, product
lol = [[1,2,3],[4,5,6],[7,8,9]]
list(chain(*(product(item, chain(*lol[index+1:])) for index, item in enumerate(lol))))

Upvotes: 1

juliomalegria
juliomalegria

Reputation: 24921

A solution using just a big list comprehension would be:

WARNING: only for list comprehension lovers

sum([[(elem,e) for e in sum(my_lists[i+1:], [])] for i,my_list in enumerate(my_lists[:-1]) for j,elem in enumerate(my_list)], [])

Result:

[(1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 7), (4, 8), (4, 9), (5, 7), (5, 8), (5, 9), (6, 7), (6, 8), (6, 9)]

Upvotes: 2

sczizzo
sczizzo

Reputation: 3206

The basic mechanism you want is called zip in functional programming. From the Haskell Prelude:

zip takes two lists and returns a list of corresponding pairs. If one input list is short, excess elements of the longer list are discarded.

There's a built-in zip() function in Python that does essentially the same thing.

Upvotes: 0

dani herrera
dani herrera

Reputation: 51705

You have a list of list (lol), then, pop first item from list of list and make cartesian product with concatenate remaining lists:

import itertools
lol = [[1,2,3],[4,5,6],[7,8,9]]
result = list()
while lol:
    l=lol.pop(0)
    o=itertools.chain(*lol)
    result += itertools.product( l,o )

result [(1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 7), (4, 8), (4, 9), (5, 7), (5, 8), (5, 9), (6, 7), (6, 8), (6, 9)]

Upvotes: 4

Related Questions