Search code examples
pythonpython-itertools

Issue with itertools.product that not list as expected


Python itertools.product module not working as expect when I'm extracting string "[1,2], [3,4], [5,6,7], [8,9]" from a json object here:

},
 "combos_matrix": "[1,2], [3,4], [5,6,7], [8,9]"
},

But it's working when I put directly numbers in ():

list(itertools.product([1,2], [3,4], [5,6,7], [8,9]))

Here is my results when I extract data from json and try the function

Json sample:

},
"combos_matrix": "[1,2], [3,4], [5,6,7], [8,9]"
},

Code by using json object:

combos_matrix = map_json["world"]["combos_matrix"]
print(combos_matrix)
combos_list = list(itertools.product(combos_matrix))
print(combos_list)

Output:

[1,2], [3,4], [5,6,7], [8,9]
[('[',), ('1',), (',',), ('2',), (']',), (',',), (' ',), ('[',), ('3',), (',',), ('4',), (']',), (',',), (' ',), ('[',), ('5',), (',',), ('6',), (',',), ('7',), (']',), (',',), (' ',), ('[',), ('8',), (',',), ('9',), (']',)]

What I'm expecting and this is the result when I give the function directly the list of numbers:

Code:

combos_list = list(itertools.product([1,2], [3,4], [5,6,7], [8,9]))
print(combos_list)

Output:

[(1, 3, 5, 8), (1, 3, 5, 9), (1, 3, 6, 8), (1, 3, 6, 9), (1, 3, 7, 8), (1, 3, 7, 9), (1, 4, 5, 8), (1, 4, 5, 9), (1, 4, 6, 8), (1, 4, 6, 9), (1, 4, 7, 8), (1, 4, 7, 9), (2, 3, 5, 8), (2, 3, 5, 9), (2, 3, 6, 8), (2, 3, 6, 9), (2, 3, 7, 8), (2, 3, 7, 9), (2, 4, 5, 8), (2, 4, 5, 9), (2, 4, 6, 8), (2, 4, 6, 9), (2, 4, 7, 8), (2, 4, 7, 9)]

Can you help on this guy, I guess I'm missing something.


Solution

  • Extracting combos_matrix from JSON objects makes it a string representation of the list, but you need the actual list, you can get it from json.loads():

    combos_matrix = map_json["world"]["combos_matrix"]
    print(combos_matrix)
    
    combos_matrix_json = f'[{combos_matrix}]'
    
    combos_list = json.loads(combos_matrix_json)
    
    combos_result = list(itertools.product(*combos_list))
    print(combos_result)
    

    Output:

    [1,2], [3,4], [5,6,7], [8,9]
    [(1, 3, 5, 8), (1, 3, 5, 9), (1, 3, 6, 8), (1, 3, 6, 9), (1, 3, 7, 8), (1, 3, 7, 9), (1, 4, 5, 8), (1, 4, 5, 9), (1, 4, 6, 8), (1, 4, 6, 9), (1, 4, 7, 8), (1, 4, 7, 9), (2, 3, 5, 8), (2, 3, 5, 9), (2, 3, 6, 8), (2, 3, 6, 9), (2, 3, 7, 8), (2, 3, 7, 9), (2, 4, 5, 8), (2, 4, 5, 9), (2, 4, 6, 8), (2, 4, 6, 9), (2, 4, 7, 8), (2, 4, 7, 9)]