首页 > 解决方案 > 蛮力算法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”对象不可订阅。我不明白,因为当我遍历列表时它将是元组,我尝试索引元组。

标签: python

解决方案


在修复评论中提到的括号问题并更改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 中获取元素。


推荐阅读