错误:解包值过多(Python)

1 投票
1 回答
5572 浏览
提问于 2025-04-18 16:10

我正在使用 Python 2.7.3

这是我代码的一部分:

linematchregex = re.compile('(\d+/\d+ \d+:\d+), (\d+\.\d+)')
.
.
with open(r'temp.txt', 'r') as f:
     f.next()
     t,temp = zip(*[p for line in for p in linematchregex.findall(line)])
     groups = itertools.groupby(f, lambda row row[0].split()[0])
     for date, group in groups:
               group = [(datetime.strptime(dt), value)
                       **for dt, value in group]**
               during_8to5 = {len(value) for value in group
                             if datetime.time(8) <= dt.time() < datetime.time(17)}
      .
      .
      .
      .
      long_title = {'\n Max AMB_TEMP Value: {:.2f} at {}, Min AMB_TEMP Value: {:.2f} at  
      {}, Mean AMB_TEMP Value: {:.2f} at {}')
      ax1.set_title(long_title.format(max(group),min(group),sum(during_8to5)/len(during_8to5))

当我运行这个模块时,出现了 'for dt, value in group' 的错误,提示 'too many values to unpack'(值太多,无法拆分)。

顺便说一下,我的文本文件数据是:21/7/2014 0:00,0.66,29.16。那我是不是应该加上 'split(',')',因为我的数据是用逗号分开的?而且我的时间是以小时:分钟的格式表示,直接用 8 和 17 这样写可以吗?

1 个回答

0

我猜“group”里的值可能长度不一样。我们来看一个简单的例子:

>>> a, b = 1, 2, 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

现在,我想你想要的是:

>>> [ (a, b) for a, b in [[1,2],[3,4], [5,6]] ]
[(1, 2), (3, 4), (5, 6)]

但实际上发生的是:

>>> [ (a, b) for a, b in [[1,2], [3,4], [5,6,7]] ]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
ValueError: too many values to unpack (expected 2)

你可以通过一些简单的方法快速检查一下,比如:

during_8to5 = {len(vals) for vals in group
                             if datetime.time(8) <= dt.time() < datetime.time(17)}

print(during_8to5)

如果结果集不是一个单一的值,那你就知道问题出在哪里了。

编辑:

我可能在“from”这一行看错了,因为你在两个地方使用了

for dt, value in group

。如果你用一个调试工具,比如pdb,把len的打印语句往上移动一层,或者使用try-except来打印group的长度,如果出现ValueError就退出程序,这样也许能帮助你找到问题。

撰写回答