Python 删除文件中最下面的3个分数
第一部分将乐队的名字和乐谱写入文件 我希望代码从文件中删除最低的3个评分带。这将有一个功能。 我该怎么做?Python 删除文件中最下面的3个分数,python,file,Python,File,第一部分将乐队的名字和乐谱写入文件 我希望代码从文件中删除最低的3个评分带。这将有一个功能。 我该怎么做? 提前感谢。因为您已经在阅读文件中的所有行 numberofbands = int(input("How many bands are there in the competition? ")) print("Input each band’s name pressing enter after each one") file = open("scores.txt","w") for
提前感谢。因为您已经在阅读文件中的所有行
numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
file = open("scores.txt","w")
for loop in range(numberofbands):
name = input("\nEnter the name of the band: ")
votes = input("Enter how many votes that band received: ")
file.write(name + "," + votes + "," + "\n")
file.close()
number_of_lines = len(open("scores.txt").readlines( ))
def removebottom3():
#code to remove bottom 3 here
removebottom3()
您可以使用按分数对行进行排序
number_of_lines = len(open("scores.txt").readlines( ))
你完全错了。我来帮你 首先,考虑使用,它是针对这种情况的。 其次,尝试将脚本逻辑划分为块(分而治之!),首先获取数据,然后排序并删除最后3个,最后将结果写入文件 下面是一个实现示例
lines = open("scores.txt").readlines()
sorted(lines,
key=lambda x : float(x.split(",")[1]),
reverse = True)
你说的“你能帮我吗”,是指“帮我做”,还是你到底需要什么帮助?请看。谢谢你的回答,如果我错了请纠正我,但我理解分数。更新。。。这是一本字典。然而,对于最终的。。。我不明白为什么要使用most_common()来搜索最多的事件,而不是最小的值。为什么[:-3]不在括号内,因为你使用的是最常见的工具?@Daniel
scores
不是标准字典,而是计数器。它有一些额外的方法,其中most_common()
按值对基础字典排序,并返回按值排序的元组列表(键,值)
[:-3]
获取整个列表,不包括最后3个值。请阅读有关计数器的Python文档,它非常清楚,只需稍加使用即可。您会发现计数器在许多类似情况下非常有用。
from collections import Counter
numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
scores = Counter()
for n in range(numberofbands):
name = input("\nEnter the name of the band: ")
vote = input("Enter how many votes that band received: ")
scores.update({name:int(votes)})
#remove the last 3
final = scores.most_common()[:-3]
#write to file
with open('scores.txt', 'w') as f:
for name, vote in final:
f.write(f'{name},{vote}\n')