如何读取 Python 中的元组列表
how to read a list of tuples in Python
所有,我正在学习 Python
,我想知道如何读取存储在 txt
文件中的元组列表,如下例所示:
我有一个名为 scores.txt
的 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
以保存 high_scores
中的 (name, score)
元组。它已通过使用 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])
所有,我正在学习 Python
,我想知道如何读取存储在 txt
文件中的元组列表,如下例所示:
我有一个名为 scores.txt
的 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
以保存 high_scores
中的 (name, score)
元组。它已通过使用 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])