Skip to content
Advertisement

How to create a list from a dict of lists that has combinations of the array elements [closed]

The question might have been worded confusingly so here I will try to make it more clear. Suppose I have a dict like x = {0: [(36, 44)], 1: [(38, 39), (38, 40), (39, 40)], 2: [(37, 41), (37, 42), (41, 42)], 3: [(43,)], 4: [(45,)]}

I want to create a list with all possible combinations of 1 element from each of the array. E.g. – [(36,44),(38,39),(37,41),(43),(45)] is one such combination, [(36,44),(38,40),(37,41),(43),(45)] is another. The final list should have all such combinations.

For now as I know the key values, I tried doing it as

JavaScript

and then finally,

y = itertools.product(arr_0, arr_1, arr_2, arr_3, arr_4)

which produces the answer

JavaScript

In a scenario where I do not the keys of the dict and the array sizes, how can I create the final array ?

Advertisement

Answer

You may use itertools.product and pass it the different arrays thta you need

JavaScript

The x.values() is a list of list of values (tuples) [[(36, 44)], [(38, 39), (38, 40), (39, 40)], [(37, 41), (37, 42)]], the * is here to expand them and pass each sublist a different parameter of the method


For you to get it, a smaller example

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement