【问题标题】:repeating a numpy array a specified number of times for itertools为 itertools 重复一个 numpy 数组指定的次数
【发布时间】:2015-04-04 03:37:40
【问题描述】:

我正在尝试编写一些代码,这些代码将为我提供 itertools 产品,用于不同数量的输入。例如,这对我有用。

test = np.array([x for x in itertools.product([0,2],[0,2],[0,2])])

这给了我想要的结果:

>>> test
array([[0, 0, 0],
       [0, 0, 2],
       [0, 2, 0],
       [0, 2, 2],
       [2, 0, 0],
       [2, 0, 2],
       [2, 2, 0],
       [2, 2, 2]])

但是,我希望能够将不同数量的列表传递给产品功能。例如:

test = np.array([x for x in itertools.product([0,2],[0,2],[0,2],[0,2])])

test = np.array([x for x in itertools.product([0,2],[0,2])])

我试过了

test = np.array([x for x in itertools.product(([0,2],) * 3)])

test = np.array([x for x in itertools.product([[0,2]]*3)])

但两者都没有给我想要的结果。当然,有一种简单的方法可以做到这一点。我将不胜感激。

【问题讨论】:

  • 您查看过itertools.product 的文档吗?
  • 在将某人引导至文档时提供链接更有用:docs.python.org/2/library/itertools.html#itertools.product
  • @whitey04:只需在控制台输入help(itertools.product)。如果我们要链接到特定版本的文档,至少要链接到当前版本。
  • 是的,我确实看过文档。我真的没有在 itertools 中看到任何似乎正是我正在寻找的东西,但这似乎是最有希望的。
  • @user14241:尊敬的,您一定没有仔细阅读。文档明确表示“例如,product(A, repeat=4) 与 product(A, A, A, A) 的含义相同。”

标签: python arrays list numpy itertools


【解决方案1】:

在我看来,您正在掌握 splat-unpack 语法:

>>> n = 3
>>> L = [0, 2]
>>> np.array([x for x in itertools.product(*([L] * n))])
array([[0, 0, 0],
       [0, 0, 2],
       [0, 2, 0],
       [0, 2, 2],
       [2, 0, 0],
       [2, 0, 2],
       [2, 2, 0],
       [2, 2, 2]])

不过,使用第二个参数 repeatitertools.product 可能更容易。

>>> np.array(list(itertools.product(L, repeat=3)))
array([[0, 0, 0],
       [0, 0, 2],
       [0, 2, 0],
       [0, 2, 2],
       [2, 0, 0],
       [2, 0, 2],
       [2, 2, 0],
       [2, 2, 2]])

【讨论】:

    【解决方案2】:

    itertools.product 支持另一个称为repeat 的参数,如itertools.product(*iterables[, repeat]) 中的那样,您可以通过它来操作叉积的维度。请注意,应明确指定此参数以消除列表内容的歧义。

    所以你的例子延伸到

    test = np.array([x for x in itertools.product([0,2],[0,2],[0,2],[0,2])])
    

    test = np.array([x for x in itertools.product([0,2], repeat = 4)])
    

    【讨论】:

    • 确保指定“重复”;否则会混淆。
    • @whitey04:您能否详细说明您希望我指定的位置?
    • ***重复***=4。您必须指定参数名称,这样它就不会认为它是列表的一部分。
    • 完美。这正是我想要的。我想我没有看足够好的文档。谢谢!
    【解决方案3】:

    你可以试试这个

    3次

     test = np.array([x for x in itertools.product(*itertools.repeat([0,2],3))])
    

    n次

     test = np.array([x for x in itertools.product(*itertools.repeat([0,2],n))])
    

    itertools.repeat([0,2],n) 这将无限重复 elem, elem, elem, ...

    【讨论】:

      【解决方案4】:

      您需要添加* 以展开列表列表:

      In [244]: list(itertools.product(*[[0,2]]*2))
      Out[244]: [(0, 0), (0, 2), (2, 0), (2, 2)]
      

      这种扩展和repeat 的使用在时序测试中是相同的。

      【讨论】:

        猜你喜欢
        • 2016-01-21
        • 2021-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-25
        • 1970-01-01
        • 2014-10-17
        • 1970-01-01
        相关资源
        最近更新 更多