我有以下代码:
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变量。
答案 0 :(得分:0)
从variable_bands = [0]
行开始,此列表的大小为 1。然后,您的代码向variable_bands
追加了五个元素,从而使该列表的大小是6,因此是ValueError
。
相反,将variable_bands = [0]
更改为variable_bands = []
。
但是,更改之后,您还必须从for question in weekday_cents_questions:
看所有的try-except块,它仍然不起作用,因为当列表为空并且您想要要获取最后一个列表,它仍然是超出范围回溯的数组索引。相反,您必须删除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]
答案 1 :(得分:0)
您应该以{{1}}开头并为空列表,否则列表中将有6个元素而不是5个元素:
variable_bands