在Python2.7.5中按特定子值对列表排序

2024-04-24 03:10:46 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑

我试过了

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和其他人。你知道吗

我需要整理一下self.openlist文件按f子值,从最低到最高。你知道吗

另外,我有很多不必要的打印在那里,只是为了帮助我跟踪程序在哪里,而我在调试它。你知道吗

任何提示都将不胜感激。下面是我的代码:

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中都有适当的标签。你知道吗

提前谢谢!你知道吗


Tags: 文件pathnameselflenisdefprint