我有以下代码:
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:要解压的值太多(预期为 5)
你能告诉我如何修复吗?我正在尝试将输入的整数分配给 variable_band 变量。
最佳答案
从 variable_bands = [0]
行开始,此列表的大小已经 1。然后,您的代码将另外五个元素附加到 variable_bands
,导致此列表的大小为 6,因此出现 ValueError
。
相反,将 variable_bands = [0]
更改为 variable_bands = []
。
但是,在更改之后,您还必须从 for question in weekday_cents_questions:
查看所有 try-except block ,它仍然无法工作,因为当列表是空的,你想得到最后一个列表,它仍然是一个数组索引超出范围的回溯。相反,您必须删除 question.format()
部分,因为它不是必需的。
你的最终代码应该是
variable_bands = []
for question in weekday_cents_questions:
try:
cents = int(input(question))
variable_bands.append(cents)
except (SyntaxError, ValueError):
variable_bands.append(0)
这是修改后程序的运行示例
You will now be asked to enter the cost per kWh for the hourly times in a 24 hour clock.
What is the tariff from the weekday time 0:00? (in cents e.g 23.5)
1
What is the tariff from the weekday time 7:00? (in cents e.g 23.5)
2
What is the tariff from the weekday time 9:00? (in cents e.g 23.5)
3
What is the tariff from the weekday time 19:00? (in cents e.g 23.5)
omg
What is the tariff from the weekday time 21:00? (in cents e.g 23.5)
4
[1, 2, 3, 0, 4]
关于Python 值错误 : too many values to unpack (For loop with nested variable),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51489246/