Home > other >  List of possible combinations of elements within a list of list
List of possible combinations of elements within a list of list

Time:09-13

I have a list that contains 2 list:

[['[email protected]', '[email protected]'], ['[email protected]', '[email protected]'], '100', '1']

How I can combine all the possible combinations between the elements of the first list (position 0) and the second list (position 1) individually and at the same time create a new list with the elements that are not in those two positions of the original list.

So the result would be like:

[ 
['[email protected]','[email protected]','100', '1'], 
['[email protected]','[email protected]','100', '1'], 
['[email protected]','[email protected]','100', '1'],
['[email protected]', '[email protected]','100', '1'] 
]

I can assume that the lists within the list will always be at position 0 and 1 but there could be multiple elements.

Thanks!

CodePudding user response:

There are better ways to do this, but here is a simple way:

  1. Create an array for storing all the results, and iterate the first array
all_arrays = []
for a in items[0]:
  1. Iterate the second array
    for b in items[1]:
  1. Create a new array consisting of a, b, and the rest of your items; and append this array to the output
        new_array = [a, b]   items[3:]
        all_arrays.append(new_array)

For more reading on generating combinations of lists, I'd suggest checking out the itertools module

  • Related