Itertools产品值错误:太多值无法解压缩(应为2)

2024-10-08 19:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个问题经常被重复,但我还没见过一个能解决这个具体问题的问题。我得到了这个函数,它取numpy数组的长度,然后取叉积:

def solve(tab, vacios):
    if vacios == 0: 
        return is_valid( tab ) #Not important here
    large = len(tab)
    for fila, col in product(range(large), repeat=(large-1)):

但我得到一个错误:

^{pr2}$

我真的不知道该怎么办,所以如果你能帮我,那就太好了,谢谢!在


Tags: 函数numpyreturnifhereisdefnot
1条回答
网友
1楼 · 发布于 2024-10-08 19:25:17

每次迭代都会产生一个large-1值的组合,因为这就是您将repeat参数设置为:

product(range(large), repeat=(large-1):

但是将值解压为两个变量filacol

^{pr2}$

如果传入一个长度不是3的tab值,那么要解包的值的数目总是错误的。在

例如,如果len(tab)为4,则生成长度为3的元组:

>>> from itertools import product
>>> large = 4
>>> list(product(range(large), repeat=large - 1))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (0, 3, 0), (0, 3, 1), (0, 3, 2), (0, 3, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 0), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 0, 3), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 0), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 0), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 0, 0), (3, 0, 1), (3, 0, 2), (3, 0, 3), (3, 1, 0), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 0), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 0), (3, 3, 1), (3, 3, 2), (3, 3, 3)]

或者将repeat硬编码到2,或者不要尝试将变量数量的值解压为固定数量的变量。在

相关问题 更多 >

    热门问题