代码之家  ›  专栏  ›  技术社区  ›  SuperCiocia

Python-有没有一种方法可以自动执行<代码>itertools.product</code>

  •  1
  • SuperCiocia  · 技术社区  · 6 年前

    我有以下代码:

    import numpy as np
    from itertools import product
    x = np.arange(-1, 2)
    a = np.array([i for i in product(x,x,x,x)])
    

    np.array([i for i in product(x,x)]) np.array([i for i in product(x,x,x)]) ... 所以我想自动化 product 所以我必须给出一个关于重复次数的论点。。。

    我试着给 产品 一个列表和一个元组,这是行不通的。

    有什么想法吗?

    3 回复  |  直到 6 年前
        1
  •  1
  •   chepner    6 年前

    product 接受一个可选的整数参数,指定要重复iterable参数的次数。

    np.array(product(x, repeat=2))
    np.array(product(x, repeat=3))
    np.array(product(x, repeat=4))
    # etc
    
        2
  •  2
  •   Daniel    6 年前

    product 对努比来说,有一个论点 repeat x 必须重复:

    def np_product(x, repeat):
        result = np.ndarray((len(x),)*repeat + (repeat,))
        for n in range(repeat):
            index = (None,) * n + (slice(None),) + (None,) * (repeat-n-1)
            result[..., n] = x[index]
        return result.reshape(-1, repeat)
    
    a = np_product(x, repeat)
    
        3
  •  0
  •   Louis Ng    6 年前
    n = 4
    lst = [x for _ in range(n)]
    [i for i in product(*lst)]