itertools.product的结果与预期不符的问题
我在使用Python的itertools.product模块时,遇到了一些问题。当我从一个json对象中提取字符串"[1,2], [3,4], [5,6,7], [8,9]"时,它没有按我预期的那样工作:
},
"combos_matrix": "[1,2], [3,4], [5,6,7], [8,9]"
},
但是当我直接在括号里放数字时,它就能正常工作:
list(itertools.product([1,2], [3,4], [5,6,7], [8,9]))
这是我从json中提取数据并尝试这个函数时的结果:
json示例:
},
"combos_matrix": "[1,2], [3,4], [5,6,7], [8,9]"
},
使用json对象的代码:
combos_matrix = map_json["world"]["combos_matrix"]
print(combos_matrix)
combos_list = list(itertools.product(combos_matrix))
print(combos_list)
输出:
[1,2], [3,4], [5,6,7], [8,9]
[('[',), ('1',), (',',), ('2',), (']',), (',',), (' ',), ('[',), ('3',), (',',), ('4',), (']',), (',',), (' ',), ('[',), ('5',), (',',), ('6',), (',',), ('7',), (']',), (',',), (' ',), ('[',), ('8',), (',',), ('9',), (']',)]
这是我期望的结果,而这是当我直接给函数一个数字列表时的结果:
代码:
combos_list = list(itertools.product([1,2], [3,4], [5,6,7], [8,9]))
print(combos_list)
输出:
[(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)]
能帮我看看这个问题吗?我觉得我可能漏掉了什么。
2 个回答
1
字典里的值是字符串,所以你需要先把这个字符串转换成列表。注意:你的字符串缺少开头的 [
和结尾的 ]
,所以在把这个字符串转换成列表的时候,需要加上这两个符号。
要把字符串转换成列表,你可以使用 ast.literal_eval
:
from ast import literal_eval
from itertools import product
dct = {"combos_matrix": "[1,2], [3,4], [5,6,7], [8,9]"}
lst = literal_eval(f"[{dct['combos_matrix']}]")
for p in product(*lst):
print(p)
输出结果是:
(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)
1
从JSON对象中提取combos_matrix会把它变成一个字符串形式的列表,但你需要的是实际的列表。你可以通过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)
输出结果:
[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)]