全部,我正在学习Python
,我想知道如何读取存储在txt
文件中的元组列表,如以下情况:
我有一个使用以下格式的txt
文件scores.txt
:
('name1', 8)
('name2', 2)
('name3', 4)
...
现在,我想读scores.txt
一个清单,说scores
,以便我可以按降序对分数进行排序,并进行一些进一步的处理。我想知道如何做到这一点。
这是维护txt
文件中存储的高分列表的一种做法。需要一个函数来从文件中读取分数,并在每次调用该函数时附加一个新分数。分数列表需要先进行排序,然后再保存回txt
文件(score.txt
)。如果score.txt
事先不存在,则将首先创建它。我在某处借了一段代码供参考,有一个可行的解决方案是:
def high_score(score):
"""Records a player's score and maintains a highscores list"""
# no previous high score file
try:
with open("high_scores.txt", "r") as f:
high_scores = [ast.literal_eval(line) for line in f]
except FileNotFoundError:
high_scores = []
#add a score // Do current stuff for adding a new score...
name = input("What is your name? ")
entry = (name, score)
high_scores.append(entry)
high_scores.sort(key = lambda x: -x[1])
high_scores = high_scores[:5] # keep only top five
# write scores to high_scores.txt
with open("high_scores.txt", "w") as f:
for score in high_scores:
f.write(str(score) + "\n")
对我来说,问题在于如何将存储在其中的字符串转换为,high_scores.txt
以int
将(name, score)
元组保存在中high_scores
。并且已经通过使用ast
模块的literal_eval
实用程序功能解决了。
import ast
with open("scores.txt") as inf:
scores = [ast.literal_eval(line) for line in inf]
scores.sort(key = lambda x: -x[1])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句