我刚刚开始学习Python,我编写了一个骰子游戏的代码,我将高分保存在一个文本文件中,最后,我想输出前5个高分。
我已经用以下结构保存了文本文件中的每个分数:名称:得分
下面是我编写的代码:
file = open ("DiceGameScores","r")
for line in file:
file_line = line.split(": ")
value = file_line[-1]
print (value)
scores = value
print (scores)
mylist = []
mylist.extend (scores)
print (mylist)
mylist.sort(reverse = True)
print (mylist[0:5])
file.close()我输出了分数和要检查的列表,当我运行它时,我得到了以下内容:
62
58
57
44
46
46
['4', '6', '\n']
['6', '4', '\n']46是程序最近的高分,它将每个数字作为列表的值,并接受代码的新行(\n)部分
我怎样才能得到前五名高分的顺序和整体数字?
发布于 2020-12-09 17:11:21
你的两个主要问题是:
使用extend...
extend接受一个可迭代(在本例中是来自文件的字符串),并将及其所有元素添加到列表中。这就是你得到['4', '6']的原因。除此之外,您只得到一个数字,因为您在循环之外执行此操作。您需要使用append添加整数,并在循环的中这样做。您还应该将分数转换为ints,以便进行适当的排序:
mylist = []
with open("DiceGameScores","r") as file:
for line in file:
file_line = line.split(':')
value = file_line[-1]
print (value)
mylist.append(int(value))
print(mylist)
mylist.sort(reverse=True)
print(mylist[:5])注意使用with打开文件--这是在Python中处理文件的惯用方法。比使用open/close要好得多。拥抱它!
发布于 2020-12-09 17:06:26
使用熊猫,您可以将文件读入数据,然后显示分数的数量,如
import pandas as pd
df = pd.read_csv("data.txt",sep=':', header=None)
df.columns = ["name","score"]
df.sort_values("score", inplace=True, ascending=False)
df.iloc[:3]显示前三名的分数
name score
3 d 78
2 c 67
1 b 56发布于 2020-12-09 17:08:15
您需要的是在循环之外声明一个列表。然后将更新的score追加到列表中。剩下的代码和你一样。
file = open("DiceGameScores", "r")
mylist = []
for line in file:
file_line = line.split(": ")
value = file_line[1]
print(alue)
scores = value
print(scores)
mylist.append(scores)
print(mylist)
mylist.sort(reverse=True)
print(mylist[0:5])https://stackoverflow.com/questions/65221230
复制相似问题