首页 > 解决方案 > 有没有更好的方法向 itertools.product 发送多个参数?

问题描述

我正在尝试从包含许多行的 2D 列表创建 itertools.product 。例如,考虑一个列表 s:

[[0.7168573116730971,
  1.3404415914042531,
  1.8714268721791336,
  11.553051251803975],
 [0.6702207957021266,
  1.2476179147860895,
  1.7329576877705954,
  10.635778602978927],
 [0.6238089573930448,
  1.1553051251803976,
  1.5953667904468385,
  9.725277699842893],
 [0.5776525625901988,
  1.0635778602978927,
  1.4587916549764335,
  8.822689900641748]]

我想在列表的 4 行之间计算 itertools.product :

pr = []
for j in (it.product(s[0],s[1],s[2],s[3])):
    pr.append(j)

这给出了 pr 的必要结果,其维度为 256,4,其中 256 是(列数 ^ 行数)。但是,有没有更好的方法将 list 的所有行作为参数发送,而不必写每一行的名称。如果要为更大的列表完成,这将很烦人。

如果 s 是 numpy.array,我猜想可以使用 numpy.meshgrid。但即使在那里,我也必须一一记下每一行作为论据。

标签: pythonlistitertools

解决方案


为此,您可以使用*Python 中的解包表示法:

import itertools as it

s = [[0.7168573116730971,
  1.3404415914042531,
  1.8714268721791336,
  11.553051251803975],
 [0.6702207957021266,
  1.2476179147860895,
  1.7329576877705954,
  10.635778602978927],
 [0.6238089573930448,
  1.1553051251803976,
  1.5953667904468385,
  9.725277699842893],
 [0.5776525625901988,
  1.0635778602978927,
  1.4587916549764335,
  8.822689900641748]]

pr = []
for j in (it.product(*s):
    pr.append(j)

它会将列表s中的每个项目发送到product函数


推荐阅读