Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将数据排序到不同的文件中_Python - Fatal编程技术网

Python 将数据排序到不同的文件中

Python 将数据排序到不同的文件中,python,Python,我需要将这个程序中的数据排序到一个.txt文件中 按字母顺序 由高到低 if usersGroup == a: with open("groupA.txt","a+") as f: f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken)) elif usersGroup == b: with open("groupB.txt","a+") as f: f

我需要将这个程序中的数据排序到一个.txt文件中

按字母顺序

由高到低

if usersGroup == a:
with open("groupA.txt","a+") as f:
    f.write("   {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))

elif usersGroup == b:
    with open("groupB.txt","a+") as f:
        f.write("   {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))

elif usersGroup == c:
    with open("groupC.txt","a+") as f:
        f.write("   {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
else:
    print("Sorry, we can not save your data as the group you entered is not valid.")

我试着在互联网上搜索如何做到这一点,但我找不到任何相关的。非常感谢您的帮助。

python附带了一个内置函数sortedl,它将返回序列l的排序副本;您甚至可以提供自己的键或比较操作,请参阅

您将首先对用户列表或对代码摘录进行操作的任何内容进行排序,然后调用输出函数

编辑:我被要求进一步简化我的答案;我认为这真的不可能做到,除了我在评论中写道:

由于您是新手,请阅读Python教程。列表和操作 列表是python中非常核心的概念,所以有好的教程吗 会让你明白我的答案


标准库中使用的排序算法在排序方法和排序函数上是稳定的。这意味着原始顺序在排序比较下绑定的项目之间保留。如果你曾经在电子表格中对列进行过排序,你就知道我在说什么

假设您的数据包含在字典列表中,如下所示:

{'correctAnswers': 3, 'username': 'Jack', 'timeTaken': 21.7}
要实现您的目标,请先按正确答案的数量,然后按名称对列表进行排序:

scores.sort(key=lambda x: x['correctAnswers'], reverse=True)
scores.sort(key=lambda x: x['username'])

你有什么具体的问题?我正在努力完成上面提到的任务。我对编码很陌生,所以我不知道你的回答是什么。你能帮我简化一下吗?简化一下:由于你是新手,请阅读Python教程。列表和列表上的操作是python中非常核心的概念,所以任何好的教程都会让您理解我的答案。