python - 蛮力算法mm
问题描述
我试图从满足数量不超过 max_quantity 的元组列表中找到最佳值。输入:
list = [('a', 1, 19), ('b', 2, 19), ('c', 1, 49), ('d', 5, 79)]
编码:
for item in list:
best_value = 0
best_quant = 0
set_value = sum(b[2] for b in item])
set_quant = sum([b[1] for b in item])
if set_value > best_value and set_quant <= max_quant:
best_value = set_value
best_quant = set_quant
print(best_value)
但是,我在 set_value 行中不断遇到类型错误,说“int”对象不可订阅。我不明白,因为当我遍历列表时它将是元组,我尝试索引元组。
解决方案
在修复评论中提到的括号问题并更改list
=> _list
(不要使用内置/类型作为变量名)之后,只需摆脱for
循环并使用 list comp。在外面_list
:
_list = [('a', 1, 19), ('b', 2, 19), ('c', 1, 49), ('d', 5, 79)]
best_value = 0
best_quant = 0
set_value = sum([b[2] for b in _list])
set_quant = sum([b[1] for b in _list])
if set_value > best_value and set_quant <= max_quant:
best_value = set_value
best_quant = set_quant
print(best_value)
您已经在列表 comp 中进行迭代,b for b in...
但您无法从已从元组中解压缩的 int 中获取元素。
推荐阅读
- mariadb - 我正在通过 Gradle 构建 jhipster 项目,第一次项目运行良好但第二次抛出异常?
- r - strsplit() 输出为 r 中的数据帧
- python - MacOS 中 python 二进制 *app 中 config.ini 的真实路径
- ms-access - MS Access 表单中的必填字段
- html - Spring Boot thymeleaf 电子邮件不包含 CSS
- servicenow - 获取 ServiceNow 服务器脚本中的所有记录值
- fiware - Orion Context Broker 安装问题
- qt - 使用 QTcreator 4.71 我如何在代码窗口中打开它的建议?
- jmeter - 什么是性能测试中的协调遗漏?
- java - Lombok 不适用于 spring-boot-maven