Python 3 - ValueError:没有足够的值来解压(预期 3,得到 2)

新手上路,请多包涵

我的 Python 3 程序有问题。我使用 Mac OS X。这段代码运行正常。

 # -*- coding: utf-8 -*-
#! python3
# sendDuesReminders.py - Sends emails based on payment status in spreadsheet.

import openpyxl, smtplib, sys

# Open the spreadsheet and get the latest dues status.
wb = openpyxl.load_workbook('duesRecords.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

lastCol = sheet.max_column
latestMonth = sheet.cell(row=1, column=lastCol).value

# Check each member's payment status.
unpaidMembers = {}
for r in range(2, sheet.max_row + 1):
payment = sheet.cell(row=r, column=lastCol).value
if payment != 'zaplacone':
    name = sheet.cell(row=r, column=2).value
    lastname = sheet.cell(row=r, column=3).value
    email = sheet.cell(row=r, column=4).value
    unpaidMembers[name] = email

# Log in to email account.
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtpObj.ehlo()
smtpObj.login('abc@abc.com', '1234')

# Send out reminder emails.
for name, email in unpaidMembers.items()
body = "Subject: %s - przypomnienie o platnosci raty za treningi GIT Parkour. " \
       "\n\nPrzypominamy o uregulowaniu wplaty za uczestnictwo: %s w treningach GIT Parkour w ." \
       "\n\nRecords show  that you have not paid dues for %s. Please make " \
       "this payment as soon as possible."%(latestMonth, name, latestMonth)
print('Sending email to %s...' % email)
sendmailStatus = smtpObj.sendmail('abc@abc.com', email, body)

if sendmailStatus != {}:
    print('There was a problem sending email to %s: %s' % (email,
    sendmailStatus))
smtpObj.quit()enter code here

当我试图将下一个值添加到 for 循环时,问题就开始了。

 # Send out reminder emails.
for name, lastname, email in unpaidMembers.items()
body = "Subject: %s - przypomnienie o platnosci raty za treningi GIT Parkour. " \
       "\n\nPrzypominamy o uregulowaniu wplaty za uczestnictwo: %s %s w treningach GIT Parkour w ." \
       "\n\nRecords show  that you have not paid dues for %s. Please make " \
       "this payment as soon as possible."%(latestMonth, name, lastname, latestMonth)
print('Sending email to %s...' % email)
sendmailStatus = smtpObj.sendmail('abc@abc.com', email, body)

终端显示错误:

 Traceback (most recent call last):
    File "sendDuesEmailReminder.py", line 44, in <module>
        for name, email, lastname in unpaidMembers.items():
ValueError: not enough values to unpack (expected 3, got 2)

原文由 Jakub Kłos 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 714
2 个回答

您可能想要分配 lastname 您正在阅读此处

lastname = sheet.cell(row=r, column=3).value

对某事;目前程序只是忘记了它

你可以在两行之后这样做,就像这样

unpaidMembers[name] = lastname, email

你的程序仍然会在同一个地方崩溃,因为 .items() 仍然不会给你三元组而是具有这种结构的东西: (name, (lastname, email))

好消息是,python 可以处理这个

for name, (lastname, email) in unpaidMembers.items():

等等

原文由 Paul Panzer 发布,翻译遵循 CC BY-SA 3.0 许可协议

1.首先应该理解错误含义

错误 not enough values to unpack (expected 3, got 2) 表示:

一个由 2 部分组成 的元组,但分配给 3 个值

我已经编写了演示代码来向您展示:


#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212

def notEnoughUnpack():
    """Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
    # a dict, which single key's value is two part tuple
    valueIsTwoPartTupleDict = {
        "name1": ("lastname1", "email1"),
        "name2": ("lastname2", "email2"),
    }

    # Test case 1: got value from key
    gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
    print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
    # gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)

    # Test case 2: got from dict.items()
    for eachKey, eachValues in valueIsTwoPartTupleDict.items():
        print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
    # same as following:
    # Background knowledge: each of dict.items() return (key, values)
    # here above eachValues is a tuple of two parts
    for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
        print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
    # but following:
    for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
        pass

if __name__ == "__main__":
    notEnoughUnpack()

使用 VSCode 调试效果:

notEnoughUnpack 克里凡李

2.对于你的代码

for name, email, lastname in unpaidMembers.items():

但错误 ValueError: not enough values to unpack (expected 3, got 2)

表示 unpaidMembers 中的每个项目(一个元组值),只有 1 个部分: email ,对应上面的代码

    unpaidMembers[name] = email

所以应该将代码更改为:

 for name, email in unpaidMembers.items():

以避免错误。

但显然你期望额外的 lastname ,所以应该将上面的代码更改为

    unpaidMembers[name] = (email, lastname)

并更好地更改为更好的语法:

 for name, (email, lastname) in unpaidMembers.items():

那么一切都很好,很清楚。

原文由 crifan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题