itertools python字典值的产物

H. *_*bri 6 python dictionary python-itertools python-3.x

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

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

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

requested = [(1, 3), (1, 4), (2, 3), (2, 4)]
Run Code Online (Sandbox Code Playgroud)

通常在传递的项目product是numpy数组时完成.

当我执行以下操作时:

list(product(list(dictionary.values())))
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

[(array([3, 4]),), (array([1, 2]),)] 
Run Code Online (Sandbox Code Playgroud)

Ray*_*ger 4

itertools.product ()函数期望参数被解包到单独的参数中,而不是保存在单个映射视图中。使用*运算符进行解包:

>>> 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)]
Run Code Online (Sandbox Code Playgroud)