错误:太多的值无法解包(Python)

2024-10-01 11:41:01 发布

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

我使用的是python2.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'i get'too many values to unpack'

我的txt文件数据是:21/7/2014 0:00,0.66,29.16 既然我的数据是用逗号分隔的,那么我应该放“split(”,“)”吗? 既然我的时间是h:m格式的,只放了8和17就可以了吗?在


Tags: infordatetimetimetitlevaluedtgroup
1条回答
网友
1楼 · 发布于 2024-10-01 11:41:01

我假设你在“组”中的值可能不是全部相等的长度。考虑下面这个简单的例子:

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

现在,我想你想要的是:

^{pr2}$

但实际情况是:

>>> [ (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)

如果结果集不包含一个值,则您知道问题所在。在

编辑:

我可能已经查过了,因为你用的是

for dt, value in group

在两个地方。如果只使用pdb之类的调试器,将len的打印上移一级,或者使用try-except来打印group的长度,然后退出程序呢。在

相关问题 更多 >