【问题标题】:Cannot pass yield value to another function无法将屈服值传递给另一个函数
【发布时间】:2020-05-14 12:45:58
【问题描述】:

我有这两个功能:

def getItems(r, c):
     **do something**
     **find and yield four values a, b, c, d**
     yield (a,b,c,d)

def mainfunction(data): 
     reader = csv.reader(records)
     for row in reader:
         a,b,c,d = getItems(row, c)
     yield (a,b,c,d)

但是,当我运行文件时,我不断收到错误:

a, b, c, d = getItems(r, c)
ValueError: not enough values to unpack (expected 5, got 1)

我不知道该怎么做!

【问题讨论】:

  • 您尝试传递给getItems 的值rc 来自哪里?
  • 是的,很抱歉 r 应该是行,而 c 是我传递的字典以获取每行中的匹配项。我已经编辑了。

标签: python function generator


【解决方案1】:

yield 将函数转换为生成器,每个yield 都是迭代器的一项。元组是另一个项目。所以你的getItem 返回一个元组的可迭代(~sequence),即使它只产生一个元组,它仍然是一个元组的迭代器。

只需将yield 替换为return。或者,如果它存在的实际原因,您需要迭代 getItem 的结果。

您还可以生成单个值,例如 getItem() 是 4 个元素的可迭代对象,但这似乎不是很有用。

【讨论】:

  • 我应该只使用yield,你建议我如何迭代yield?
  • 那...没有任何意义。但是您可以使用for a, b, c, d in getItem(),也可以将yield a, b, c, d 替换为yield a; yield b; yield c; yield d。不过,两者似乎都很愚蠢。
  • 使用第一种方法,我得到一个新的错误:yield (a, b, c, d) UnboundLocalError: local variable 'c' referenced before assignment
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
相关资源
最近更新 更多