首页 > 解决方案 > 在 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

有什么建议吗?

标签: pythonlistdictionary

解决方案


例外是因为您使用itemgetter了错误的参数类型:str。正如例外所说。

如果您想按的值排序totalCost并且它始终是第 8 项,我会选择:

排序方式key= lambda x: x[7]['totalCost']


推荐阅读