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)
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)
| 归档时间: |
|
| 查看次数: |
3521 次 |
| 最近记录: |