Python 2.7:从列表中弹出

时间:2017-03-22 20:46:18

标签: python python-2.7 sorting csv

我目前正在制作像太空入侵者这样的游戏。游戏将从游戏中获取所有分数,对它们进行排序,然后将分数保存到csv文件中。我这样做的方法是将分数保存到未排序的csv文件,读取和排序这些值,然后将排序的值保存到不同的排序的csv文件。但是,我希望我的csv文件只存储前10个分数。这是我目前用于此过程的代码:

if col:
    with open("rec_Scores.csv", "ab") as f:     #adding new score into unsorted file
        w = csv.writer(f, delimiter = ",")
        w.writerow([curr_score])


    with open ("rec_Scores.csv", "rb") as csvfile:  #reads file, converts values to integers and sorts file (including the new score)
        r = csv.reader(csvfile)
        scores = list(r)
        scores_int = [int(score[0]) for score in scores]
    bubbleSort(scores_int)
    scores_int.pop()
    print(scores_int)

    with open("srt_Scores.csv", "wb") as sortfile:   #Should write a new csv file every time containing the sorted scores
        w = csv.writer(sortfile, delimiter = ",")
        w.writerows([[v] for v in scores_int])

我知道这不是执行此过程的最有效方法,但它主要起作用。如果有人能帮助我让程序只存储前10个分数,那将非常感激。

P.S: 这是我第一次使用Python中的csv文件,所以我知道它是混乱和低效的,但分数存储和排序很好,我只想限制值的数量。

1 个答案:

答案 0 :(得分:1)

如果上面的代码在其他方面“正常工作”(你可以添加新的分数,阅读和排序),那么要将它们限制为10,你需要做的就是切掉前10个分数。替换此行:

Joined

......用这个:

scores_int.pop()

假设您的最佳分数排在第一位。如果没有,那么你想要最后 10个项目:

scores_int = scores_int[:10]

在列表中有10个项目之前执行此操作是安全的。在这种情况下,任何给定的行都不会做任何事情。