【问题标题】:Itertools product ValueError: too many values to unpack (expected 2)Itertools 产品 V​​alueError:解包的值太多(预期为 2)
【发布时间】:2016-06-20 06:18:19
【问题描述】:

我知道这个问题被重复了很多次,但我还没有看到一个处理这个特定问题的问题。我得到了这个函数,它取一个 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)):

但我收到此错误:

ValueError: too many values to unpack (expected 2)

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

【问题讨论】:

    标签: python python-3.x numpy itertools


    【解决方案1】:

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

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

    但是将值解包到两个变量中,filacol

    for fila, col in product(range(large), repeat=(large-1)):
    

    如果您传入长度不是 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)]
    

    要么硬编码repeat2,要么不要尝试将可变数量的值解压成固定数量的变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-29
      • 2020-05-11
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 2017-12-14
      相关资源
      最近更新 更多