对从文件导入的列表排序。。。Python

2024-07-04 03:17:57 发布

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

我对python非常陌生,我希望我不会错过其他地方的修复程序。我有一个简单的程序,这是我买的一本书中的练习之一,我遇到了一个问题。我有一个程序可以打开一个文件并将其写入列表。然后用户可以用输入更新列表,当用户退出时,它用最新的内容更新列表。除了sort选项之外,一切正常。它显示文件中的分数,前面有一个单引号,并且在程序运行时没有更新分数。它也根本不分类。我试过很多不同的方法来做到这一点。我相信从长远来看,这并不重要,但我想弄清楚。在

这是密码

# High Scores
# Demonstrates list methods

scores = []
try:
    text_file = open("scores.txt", "r")
    for line in text_file:
        scores.append(line.rstrip("\n"))

    text_file.close()

except:
    raw_input("Please verify that scores.txt is placed in the correct location and run again")



choice = None
while choice != "0":


    print \
    """
    High Scores Keeper

    0 - Exit
    1 - Show Scores 
    2 - Add a Score
    3 - Delete a Score 
    4 - Sort Scores
    """

    choice = raw_input("Choice: ")
    print

    # exit
    if choice == "0":
        try:
            output_file = open("scores.txt" , "w")
            for i in scores:
                output_file.write(str(i))
                output_file.write("\n")

            output_file.close()
            print "Good-bye"
        except:
            print "Good-bye.error"

    # list high-score table
    elif choice == "1":
        print "High Scores"
        for score in scores:
            print score

    # add a score
    elif choice == "2":
        score = int(raw_input("What score did you get?: "))
        scores.append(score)

    # delete a score
    elif choice == "3":
        score = int(raw_input("Delete which score?: "))
        if score in scores:
            scores.remove(score)
        else:
            print score, "isn't in the high scores list."

    # sort scores
    elif choice == "4":
        scores.sort()
        scores.reverse()
        print scores

    # some unknown choice
    else:
        print "Sorry, but", choice, "isn't a valid choice."


raw_input("\n\nPress the enter key to exit.")

Tags: in程序列表inputoutputrawsortfile
2条回答

当您从文件中添加分数时,您将它们作为字符串添加:scores.append(line.rstrip("\n"))。但是,当你在程序中添加分数时,你就是把它们作为整数相加:int(raw_input("What score did you get?: "))。在

当Python对包含字符串和整数的列表进行排序时,它将根据字符顺序对字符串进行排序(so'1' < '12' < '3'),并对整数进行单独排序,将整数放在字符串之前:

>>> sorted([1, 8, '11', '3', '8'])
[1, 8, '11', '3', '8']

大概是在字符后面和前面都打印出一个引号,就像这里一样(表示它是一个字符串)。在

所以,当你开始读取文件时,把它们变成一个整数,就像你读用户输入一样。在


其他提示:

  • scores.sort(reverse=True)将按相反的顺序排序,而不必遍历列表两次。在
  • except:通常不是一个好主意:这样做绝对可以捕捉到程序的任何问题,包括用户点击^C试图退出,系统内存不足等等。您应该将except Exception:作为一个包罗万象的方法来获取可以恢复的异常,但不能恢复这些类型的系统错误,或者更具体的异常当您只想处理某些类型时。在

如果在你的文本文件中,每行只有一个分数,最好的方法是将分数转换成整数,同时接受这样的输入。在

scores = []
try:
    text_file = open("scores.txt", "r")
    for line in text_file:
        scores.append(int(line.strip()))
except:
    text_file.close()

实际上,你接受输入的方式是把一些数字留作字符串。处理这类问题的最好方法是在排序之前打印数组并查看它。祝你一切顺利。在

相关问题 更多 >

    热门问题