简体   繁体   中英

how to remove last 3 data in python from a doc

I've been attempting for a while to make it so that my quiz will delete data which had been done by the specific person 3 times ago. so if there is 4 people who have done the quiz and one of them is doing it for the forth time, I want it to delete the first time, this is the coding I have got so far

its not all of it, but you can see what I am doing

else:
    print(" ")
    print("Well Done",name,"!")
    print("Thankyou for taking this quiz")
    print("Your Score is ",finalscore,"/ 10.")
file=open(classname".txt", 'a')
file.write(str(name + " "))
file.write(str(finalscore))
file.write(str(":""\n"))
file.close()
print("Do you wish to view people's previous results?")

previousscore=input()
if previousscore=="yes".lower():
    sorter=input()
    if sorter=='1':
    reader=csv.reader(open(classname".txt"),delimiter=':')
    with open(classname".txt", 'r') as f:
        for line in sorted(f):
            print(line, end='')

I've only got it so far that it puts it into alphabetical order perfectly, but I need it to delete data. The data shows up like this in the document; Keanu 10: Keanu 10: Keanu 10: Jack 7: Jack 3: Jack 3: Harry 10: Harry 8: Jordan 7: Jordan 10: Keanu 1:

The python coding then changes it to this; Harry 10: Harry 8: Jack 3: Jack 3: Jack 7: Jordan 10: Jordan 7: Keanu 10: Keanu 10: Keanu 10: Keanu 1: Keanu 1:

But I want it to look like this; Harry 10: Harry 8: Jack 3: Jack 3: Jack 7: Jordan 10: Jordan 7: Keanu 10: Keanu 10: Keanu 2:

so it only shows the last three attempts :) any help will be so helpful, but keep in mind I have only just started python... so don't get too technical ;)

This sounds a lot like a class assignment. So my advice to you would be this:

  1. Read the lines of text from the file.
  2. Determine the name (key) from the line.
  3. Add the score to a dictionary of lists. d[key] = list(score, score, score, ...)
  4. Shorten the list if it's too long.

After that, you'll have the "most recent" scores for each player in a list by that player's name. You can sort however you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM