Concrete list list processing in python ... itertools?

I have a list of lists, every first element of a list of the second level can be considered as a kind of meta information 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)] 

Nature is available here:

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

I need to build another list in which each of the various possible combinations is grouped by the sequences of each "nature" (that is, natures )

the result should be shown in the example below

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

I think this can be done with the clever use of some itertools package, but I am completely lost inside it, can someone help me on the proper use of itertools ( groupby and product possible?)

Regards

+4
source share
2 answers

First you can use itertools.groupby to group elements by nature, then you can use itertools.product to form all combinations of elements 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)]] 
+4
source

If you first convert your natures to a list of tuples / lists, you can continue as indicated in this answer :

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

Source: https://habr.com/ru/post/1500494/


All Articles