Python 为itertools重复numpy数组指定次数
我正在尝试编写一些代码,为不同数量的输入提供itertools产品。例如,这对我来说很有效Python 为itertools重复numpy数组指定次数,python,arrays,list,numpy,itertools,Python,Arrays,List,Numpy,Itertools,我正在尝试编写一些代码,为不同数量的输入提供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],
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],) * 3)])
及
但两者都没有给我想要的结果。当然有一个简单的方法可以做到这一点。如果有任何帮助,我将不胜感激。在我看来,您正在掌握splat解包语法:
>>> 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]])
但是,使用第二个参数repeat
到itertools.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]])
支持另一个名为repeat
的参数,如itertools.product(*iterables[,repeat])
中的参数,通过该参数可以操作叉积的维度。注意,为了消除列表内容的歧义,应该显式指定此参数
因此,您的示例扩展到
test = np.array([x for x in itertools.product([0,2],[0,2],[0,2],[0,2])])
到
您需要添加
*
以展开列表列表:
In [244]: list(itertools.product(*[[0,2]]*2))
Out[244]: [(0, 0), (0, 2), (2, 0), (2, 2)]
在定时测试中,此扩展和重复的使用是相同的 你可以试试这个三次:
test = np.array([x for x in itertools.product(*itertools.repeat([0,2],3))])
test = np.array([x for x in itertools.product(*itertools.repeat([0,2],n))])
n次:
test = np.array([x for x in itertools.product(*itertools.repeat([0,2],3))])
test = np.array([x for x in itertools.product(*itertools.repeat([0,2],n))])
重复([0,2],n)这将重复元素,元素,元素。。。无限次或最多n次,*在itertools前面是解包所有元素您是否查看了
itertools.product
的文档?在引导某人访问文档时提供链接更有用:@whitey04:只需在控制台键入帮助(itertools.product)
。如果我们要链接到文档的特定版本,至少要链接到当前版本。是的,我看过文档。我在itertools中确实没有看到任何与我所寻找的完全相同的东西,但这似乎是最有希望的。@user14241:恕我直言,您一定没有仔细阅读。文档明确地说“例如,产品(A,repeat=4)与产品(A,A,A,A)的含义相同。”确保指定“repeat”;否则它会变得混乱。@whitey04:你能详细说明你想让我指定在哪里吗?***重复***=4。您必须指定参数名,这样它才不会认为它是列表的一部分。完美。这正是我要找的。我想我对文档看得不够好。谢谢
test = np.array([x for x in itertools.product(*itertools.repeat([0,2],n))])