4

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

user2468222
  • 245
  • 1
  • 9
  • 2
    `natures = {subl[-1] for subl in L}` would be a little more concise and performant, not to mention consistent (as sets have no order). – Martijn Pieters Sep 04 '13 at 10:45

2 Answers2

4

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)]]
tobias_k
  • 81,265
  • 12
  • 120
  • 179
1

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)]
Community
  • 1
  • 1
Johannes Charra
  • 29,455
  • 6
  • 42
  • 51