python - python 字典值的 itertools 产品

标签 python python-3.x dictionary python-itertools

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

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

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

requested = [(1, 3), (1, 4), (2, 3), (2, 4)]

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

当我执行以下操作时:

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

我得到以下输出:

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

最佳答案

itertools.product()函数期望参数被解压缩到单独的参数中,而不是保存在单个映射 View 中。使用 * 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)]

关于python - python 字典值的 itertools 产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40869998/

相关文章:

python - 如何让 pygtk 条目只接受 float ?

python - 如何在 alpine linux 上安装 python?

python - 为什么我不能对这个列表进行排序?

python - Elasticsearch-Python-具有刷新功能的批量助手API

python - NetworkX 图形对象不可订阅

C# - 如何用一个键和两个值编写一个集合(字典?)

Objective-C:使用自定义对象键从 NSMutableDictionary 获取值

python - 从最后一个超链接标签获取文本

python - 如何在不丧失键盘/鼠标控制的情况下实现自动化(类似于 selenium 的受控窗口)

python - 如何访问数据框中包含字典字符串数据的列的内容