python - 在 python 上订购带有字典的列表
问题描述
我有这个:
def removeFromFront(node, front):
tmpFront = front
flagFound = False
for i in range(len(tmpFront)):
for j in (range(len(tmpFront[i]) - 3)):
if tmpFront[i][j] == node[j]:
flagFound = True
else:
flagFound = False
break
if (flagFound):
if (tmpFront[i][5]['realCost'] + tmpFront[i][6]['heuristicEstimation']) > (node[5]['realCost'] + node[6]['heuristicEstimation']):
tmpFront.pop(i)
tmpFront.insert(i, node)
else:
tmpFront.append(node)
if (len(tmpFront) > 1):
#sorted(tmpFront, key=lambda k: k['totalCost'], reverse = False)
tmpFront.sort(key=operator.itemgetter('totalCost'))
foundFlag = False
if (len(tmpFront) == 0):
tmpFront.append(node)
return tmpFront
前面是这样的: 前面:
[[3, ['E', 'NO'], ['P1', 'NO'], ['P2', 'NO'], ['P3', 'NO'], {'realCost': 0}, {'heuristicEstimation': 15},{'totalCost': 29}]]
[[3, ['P1', 'NO'], ['E', 'Yes'], ['P2', 'NO'], ['P3', 'NO'], {'realCost': 1}, {'heuristicEstimation': 15},{'totalCost': 29}], [3, ['P3', 'NO'], ['P1', 'NO'], ['P2', 'Yes'], ['E', 'NO'], {'realCost': 1}, {'heuristicEstimation': 28},{'totalCost': 29}]]
我得到以下信息:
search_algorithm_front_queue.py", line 383, in removeFromFront
tmpFront.sort(key=operator.itemgetter('totalCost'))
TypeError: list indices must be integers or slices, not str
有什么建议吗?
解决方案
例外是因为您使用itemgetter
了错误的参数类型:str
。正如例外所说。
如果您想按的值排序totalCost
并且它始终是第 8 项,我会选择:
排序方式key= lambda x: x[7]['totalCost']
推荐阅读
- java - 比较两个数组的值
- python - 在没有模型的情况下使用 django
- angular - 使用 jsPDF 将 Angular10 反应式表单转换为 PDF
- sql - Oracle如何列出两个日期之间月份的最后几天
- qt - 我应该在其他方法中使用插槽吗
- c++ - For循环显示存储在数组中的不正确信息
- python - 如何使用滚动、俯仰和偏航与我的 3-D 点融合以形成 3-D 表面?
- reactjs - 无法通过 Reactjs 在 Springboot Security 中进行身份验证
- python - BeautifulSoup 仅识别 5 个表中的 2 个
- nginx - Nginx有条件地允许所有人根据IP响应子路由