python - 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 变量。
解决方案
您应该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)
推荐阅读
- xcode - Xcode 构建突然失败 (Flutter/Dart)
- javascript - 当 if 正确时,如何使此代码像 else 语句不存在一样工作,并且对 else 语句同样执行相同的操作
- flutter - 错误'参数类型'bool Function(EmployeeDetails)'不能分配给参数类型'bool Function(SalesDetails)?飘飘然
- ruby - Ruby NetSFTP:尝试下载文件时出现奇怪错误
- git - git diff 两个哈希,显示 repo 文件大小差异
- c++ - 请谁能解释一下为什么这个排列代码不起作用
- postgresql - 正确挂载到磁盘后 Docker 卷为空
- r - 未找到对象的心理阿尔法鞋错误
- ios - 如何解决 Intune iOS 包装错误“指定了无效的签名证书”
- flutter - 如何在颤动中绘制半圆的容器