user2468222
user2468222

Reputation: 245

specific handling of list of list in python... itertools?

i have list of list, each first items of the second level list can be seen as a kind of metainformation about its nature.

# simple sample, real data are much more complex, but it can be schematized as this one
L = [('n0', 1), ('n1', 4), ('n1', 2), ('n2', 5)] 

natures are available here:

natures = list(set(zip(*L)))[0]

i need to build another list having each of each different possible combinations grouping them by consecutive of each "nature", (that is the natures)

a result should be from the example below

R = [
     [('n0', 1), ('n1', 4), ('n2', 5)],
     [('n0', 1), ('n1', 2), ('n2', 5)]
]

i think that this can be done cleverly using some of the itertools package, but i'm totally lost inside of it, can someone help me on the right itertools stuff to use (groupby and product maybe ?)

best regards

Upvotes: 4

Views: 94

Answers (2)

tobias_k
tobias_k

Reputation: 82899

First you can use itertools.groupby to group elements by their nature, then you can use the itertools.product function to form all combinations of items from different natures.

L = [('n0', 1), ('n1', 4), ('n1', 2), ('n2', 5)] 

from itertools import groupby, product
groups = [list(group) for key, group in groupby(L, lambda x: x[0])]
R = map(list, product(*groups))
print R

Output:

[[('n0', 1), ('n1', 4), ('n2', 5)], [('n0', 1), ('n1', 2), ('n2', 5)]]

Upvotes: 4

Johannes Charra
Johannes Charra

Reputation: 29923

If you transform your natures into a list of tuples/lists first, you can proceed as mentioned in this answer:

>>> from itertools import product
>>> natures = [[1], [2, 4], [5]]
>>> list(product(*natures))
[(1, 2, 5), (1, 4, 5)]

Upvotes: 1

Related Questions