编辑
我试过了
self.openlist.sort(key = lambda d: (d['f']))
和
import operator
self.openlist.sort(key = operator.itemgetter('f'))
并且都因 AttributeError 而崩溃:节点实例没有属性“ getitem ”
结束编辑
这可能是由于我对 Python 的一般不熟悉,但我无法通过搜索找到我的问题的答案,所以我在这里问。
我正在编写一个 A* 程序来查找城市之间的最短路径。
我将每一步我可以前往的所有城市都存储在一个列表 self.openlist 中,当我处理它们时,我会为它们分配所有子值,例如 self.openlist.g、self.openlist.h、self。 openlist.f 等。
我需要按 f 子值从最低到最高对 self.openlist 进行排序。
另外,我有很多不必要的打印,只是为了帮助我在调试程序时跟踪程序的位置。
任何提示将不胜感激。下面是我的代码:
import adata
class AS:
def __init__(self, startcity, goalcity, tracefunc):
self.startcity = startcity
self.goalcity = goalcity
self.tracefunc = tracefunc
self.openlist = [Node([startcity])]
self.closedlist = []
self.openlist[0].name = startcity
self.openlist[0].path = startcity
def astar_run(self, dbg=""):
while self.openlist:
if self.openlist[0].name == self.goalcity:
print self.openlist[0].path
return self.openlist[0]
else:
print "Current city", self.openlist[0].name
c2 = Roads(self.openlist[0].name)
templist = []
print "c2 contains", c2
print "Templist is", templist
x = 1
print "Length of c2", len(c2)
for i in range(0, len(c2)):
print "Test point", x
print "i value is now:", i
print c2[i]
templist.append(Node(c2[i]))
templist[i].name = c2[i]
templist[i].g = Distance(self.openlist[0].name, c2[i]) + self.openlist[0].g
templist[i].h = Distance(c2[i], self.goalcity)
templist[i].f = templist[i].g + templist[i].h
templist[i].path = self.openlist[0].path + ", to " + c2[i]
self.openlist.append(templist[i])
print "x value is now:", x
x = x + 1
print self.openlist[i].name
self.closedlist.append(self.openlist[0].name)
del self.openlist[0]
p = 0
q = len(self.openlist)
while p in range(0, q):
print "Openlist", p, "is", self.openlist[p].name
if self.openlist[p].name in self.closedlist:
print "Deleting", self.openlist[p]
del self.openlist[p]
p = p - 1
q = len(self.openlist)
p = p + 1
#print "Openlist", p, "is now", self.openlist[p].name
print "Closedlist is", self.closedlist
def Roads(city):
c1 = adata.roadlist(city)
return c1
def Distance(city1, city2):
c3 = adata.dist(city1, city2)
return c3
class Node:
def __init__(self, path=[], f=0, g=0, h=0):
self.path = path[:]
self.name = []
self.f = f
self.g = g
self.h = h
另外,我意识到我在 def 上的标签已经丢失,将代码转移到这个网站,我很抱歉。但是,所有这些都在我的 py.
提前致谢!