我有一个 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/