Python 按实体值对tkinter中列表框中的项目进行排序

Python 按实体值对tkinter中列表框中的项目进行排序,python,algorithm,tkinter,listbox,records,Python,Algorithm,Tkinter,Listbox,Records,我有一个排行榜,里面有一些童子军的信息。此信息的结构如下:ID、forname、姓氏、points。此信息存储在文件中,但在文件中没有顺序。我不想改变这个 我希望在更新列表框时(当我调用calcPoints()函数时),它会根据记录中的点实体,从最大点到最小点,对侦察员进行排序。下面是我的calcPoints()方法的代码 谢谢 def _calcPoints(): mainWin._leaderboard.delete(0,END) with open(temp

我有一个排行榜,里面有一些童子军的信息。此信息的结构如下:
ID、forname、姓氏、points
。此信息存储在文件中,但在文件中没有顺序。我不想改变这个

我希望在更新列表框时(当我调用
calcPoints()
函数时),它会根据记录中的点实体,从最大点到最小点,对侦察员进行排序。下面是我的
calcPoints()
方法的代码

谢谢

def _calcPoints():
        mainWin._leaderboard.delete(0,END)
        with open(tempFileName,'a') as ft:
            for sc in self._Scouts:
                sc._addPoints(-int(sc._getPoints()))
                with open(badgeFile,"r") as fb:
                    lines = fb.readlines()
                    for line in lines:
                        if sc._getID() == line.split(":")[0]:
                            badge = ((line.split(':')[1]).split(',')[0])
                            if badge == "Core":
                                sc._addPoints(5)
                            elif badge == 'Activity':
                                sc._addPoints(1)
                            elif badge == 'Challenge':
                                sc._addPoints(3)
                            elif badge == 'Activity Pack':
                                sc._addPoints(5)
                ft.write(sc.getInfo() + "\n")
        os.remove(leadFile)
        with open(leadFile,"a") as f:
            with open(tempFileName,"r") as ft:
                lines = ft.readlines()
                for line in lines:
                    f.write(line)
        os.remove(tempFileName)
        mainWin.addScoutsLeaderboard()
        return

只需调用sorted,按每行中的最后一个元素排序,即
,使用
reverse=True
将从高到低排序:

lines = sorted(fb,key=lambda x: float(x.rsplit(":",1)[1]),reverse=True)
不确定数据在哪个文件中,因此您的文件对象和分隔符应该与实际文件匹配,如果您有一个标题,则需要添加
header=next(fb)

如果单独使用这些值,您可能会发现csv模块更适合:

import csv
with open(badgeFile,"r") as fb:
    r = csv.reader(fb,delimiter=":")
    lines = sorted(r, key=lambda x: float(x[1]), reverse=True)
    for fid,fname,sname,pnts in lines:
另一方面,您只需要在实际需要列表时调用
.readlines()
,如果不需要,您可以在file对象上迭代