python字典值的itertools产品

2024-10-01 15:45:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python字典,字符串作为键,numpy数组作为值:

dictionary = {'first': np.array([1, 2]), 'second': np.array([3, 4])}

现在我想使用itertoolsproduct创建以下列表:

^{pr2}$

当传递给product的项是numpy数组时,通常会这样做。在

当我执行以下操作时:

list(product(list(dictionary.values())))

我得到了以下输出:

[(array([3, 4]),), (array([1, 2]),)] 

Tags: 字符串numpy列表dictionary字典np数组product
1条回答
网友
1楼 · 发布于 2024-10-01 15:45:22

itertools.product()函数要求将参数解压为单独的参数,而不是保存在单个映射视图中。使用^{} operator进行解包:

>>> import numpy as np
>>> from itertools import product
>>> dictionary = {'first': np.array([1, 2]), 'second': np.array([3, 4])}
>>> list(product(*dictionary.values()))
[(1, 3), (1, 4), (2, 3), (2, 4)]

相关问题 更多 >

    热门问题