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


i have list of list, each first items of second level list can seen kind of metainformation nature.

# simple sample, real data more complex, can schematized 1 l = [('n0', 1), ('n1', 4), ('n1', 2), ('n2', 5)]  

natures available here:

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

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

a result should example below

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

i think can done cleverly using of itertools package, i'm totally lost inside of it, can me on right itertools stuff use (groupby , product maybe ?)

best regards

first can use itertools.groupby group elements nature, can use itertools.product function form combinations of items different natures.

l = [('n0', 1), ('n1', 4), ('n1', 2), ('n2', 5)]   itertools import groupby, product groups = [list(group) 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)]] 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -