[英]order a list with dictionaries on 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']
排序key= lambda x: x[7]['totalCost']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.