Home > Blockchain >  In a list of lists duplicate the array that contains a list inside per each element that is inside t
In a list of lists duplicate the array that contains a list inside per each element that is inside t

Time:09-01

I am trying to classified and split some data in python 2.7

I have this 3D list/array:

data = [
[['[email protected]'],['[email protected]','[email protected]'],'a','b'],
['a',['[email protected]','[email protected]','[email protected]'],['[email protected]'],'b'],
[['t3'],['y1','y2','y3','y4'],'a','b']
['b',['[email protected]','[email protected]'],'a',['[email protected]','[email protected]']]
]

We can imagine one of the elements inside the list will be the SENDER and the other the RECEIVER and we must duplicate in order to fulfill all the possible combinations.

So the result is like:

result = [
['[email protected]','[email protected]','a','b'],
['[email protected]','[email protected]','a','b'],
['a','[email protected]','[email protected]','b'],
['a','[email protected]','[email protected]','b'],
['a','[email protected]','GOKU@whitelist','a','b'],
['t3','y1','a','b'],
['t3','y2','a','b'],
['t3','y3','a','b'],
['t3','y4','a','b'],
['[email protected]','[email protected]','a','b'],
['[email protected]','[email protected]','a','b'],
['[email protected]','[email protected]','a','b'],
['[email protected]','[email protected]','a','b'],
]

We create n lenght list inside the list because we have n elements inside the third list.

CONSIDERATIONS:

1- The index may change. It will not always be position 1.

2- There will always be more just 1 inner list (1 for the sender and 1 for the receiver).

3- The order of how the data is displayed does not matter (the most important thing is that the combinations exist).

4- Finally we have to flatten the list

CodePudding user response:

If in the rows of the input you would wrap all non-list items (a and b) into lists, then this task translates to getting for each row the Cartesian product of its members. And for that you can use itertools.product:

import itertools

data = [
    [['[email protected]'],['[email protected]','[email protected]'],'a','b'],
    ['a',['[email protected]','[email protected]','[email protected]'],['[email protected]'],'b'],
    [['t3'],['y1','y2','y3','y4'],'a','b'],
    ['b',['[email protected]','[email protected]'],'a',['[email protected]','[email protected]']]
]

result = [combi 
    for row in data
    for combi in itertools.product(
        *(item if isinstance(item, list) else list(item) for item in row)
    )
]
  • Related