首页 > 解决方案 > Python ValueError:解包的值太多(带有嵌套变量的 For 循环)

问题描述

我有以下代码:

col_cp1_tariff_time_weekday_1_hour = 0
col_cp1_tariff_time_weekday_2_hour = 7
col_cp1_tariff_time_weekday_3_hour = 9
col_cp1_tariff_time_weekday_4_hour = 19
col_cp1_tariff_time_weekday_5_hour = 21


weekday_cents_questions = [
    "What is the tariff from the weekday time %d:00? (in cents e.g 23.5)\n" % (col_cp1_tariff_time_weekday_1_hour),
    "What is the tariff from the weekday time %d:00? (in cents e.g 23.5)\n" % (col_cp1_tariff_time_weekday_2_hour),
    "What is the tariff from the weekday time %d:00? (in cents e.g 23.5)\n" % (col_cp1_tariff_time_weekday_3_hour),
    "What is the tariff from the weekday time %d:00? (in cents e.g 23.5)\n" % (col_cp1_tariff_time_weekday_4_hour),
    "What is the tariff from the weekday time %d:00? (in cents e.g 23.5)\n" % (col_cp1_tariff_time_weekday_5_hour)]


print("You will now be asked to enter the cost per kWh for the hourly times in a 24 hour clock.")

variable_bands = [0]

for question in weekday_cents_questions:
    try:
        q = question.format(variable_bands[-1])
        cents = int(input(q))
        variable_bands.append(cents)
    except (SyntaxError, ValueError):
        variable_bands.append(0)

[col_cp1_tariff_time_weekday_1_cents,
 col_cp1_tariff_time_weekday_2_cents,
 col_cp1_tariff_time_weekday_3_cents,
 col_cp1_tariff_time_weekday_4_cents,
 col_cp1_tariff_time_weekday_5_cents] = variable_bands

print(variable_bands)

当我执行时,我收到错误:ValueError: too many values to unpack (expected 5)

你能告诉我如何解决吗?我正在尝试将输入的整数分配给 variable_band 变量。

标签: python

解决方案


您应该variable_bands以空列表开始您的列表,否则您的列表中将有 6 个元素而不是 5 个:

# Start an empty list
variable_bands = []

for question in weekday_cents_questions:
    try:
        # Check if it is empty, otherwise you'll get an IndexError
        if variable_bands == []:
            q = question.format(0)
        else:
            q = question.format(variable_bands[-1])
        cents = int(input(q))
        variable_bands.append(cents)
    except (SyntaxError, ValueError):
        variable_bands.append(0)

推荐阅读