太多的值无法在收益中解包 [英] too many values to unpack in a yield

查看:34
本文介绍了太多的值无法在收益中解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个练习,其中 Item 是一个类,当我运行 testAll 时,我有一个 valueError.产量假设只返回 2 个值,即 2 个袋子的内容:

this is an exercise where Item is a class, and when I run testAll I have a valueError. The yield is suppose to return just 2 values, the content of 2 bags:

> Traceback (most recent call last):
  File "<pyshell#63>", line 1, in <module>
    testAll()
  File "/Downloads/L18_code.py", line 101, in testAll
    pset1,pset2=yieldAllCombos(items)
ValueError: too many values to unpack

def buildItems():
return [Item(n,v,w) for n,v,w in (('clock', 175, 10),
                                  ('painting', 90, 9),
                                  ('radio', 20, 4),
                                  ('vase', 50, 2),
                                  ('book', 10, 1),
                                  ('computer', 200, 20))]
def yieldAllCombos(items):
"""
Generates all combinations of N items into two bags, whereby each item is in one or
zero bags.

Yields a tuple, (bag1, bag2), where each bag is represented as a list of which item(s)
are in each bag.
"""
N = len(items)
# enumerate the 3**N possible combinations
for i in xrange(3**N):
    combo1 = []
    combo2 = []
    for j in xrange(N):
        # test bit jth of integer i
        if (i >> j) % 3 == 1:
            combo1.append(items[j])
        elif (i>>j) % 3 == 2:
            combo2.append(items[j])        
    yield(combo1,combo2)
def testAll():
    items = buildItems()
    pset1,pset2=yieldAllCombos(items)

推荐答案

你在循环中一次 yield 两个项目,所以你必须一次捕获两个:

You yield two items at a time in your loop, so you have to catch two at a time:

for pset1, pset2 in yieldAllCombos(items):
    ...

这篇关于太多的值无法在收益中解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆