如何在Python中读取元组列表

daiyue

全部,我正在学习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.txtint(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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在python中聚合元组列表?

如何在Python中搜索元组列表

如何在Python中绘制元组列表?

如何在Python中的元组列表中枚举()?

如何在python中返回元组中的对象列表?

如何在python中的列表中添加元组

如何在Python中绘制以元组表示的线列表?

如何在python中解压缩元组列表?

如何在Python中打印不带括号的元组列表

如何在 Python 中散列列表元组

如何在Python中展平嵌套元组列表?

如何在 Python 中根据元组内容拆分列表

如何在 Python 中创建可更新的元组列表?

如何在python中解压缩元组列表

从Haskell中的文本文件读取后如何在列表中添加元组

如何在python中通过子串找到元组列表中的元组?

如何在Python中将元组列表收集到一个元组中?

如何在元组中拆分列表?

如何在python 3.3中将嵌套的列表列表转换为元组列表?

如何在元组列表中修改元组的每个元素

如何在元组列表中连接元组内的元素?

如何在列表中查找重叠的元组并返回重叠的元组

如何在Javascript中读取Python列表[在Django模板中]

如何在python中的字典列表中读取字典

如何在Python中对元组列表列表进行平面映射?

如何在Python中创建一个空列表或空列表元组?

如何在 Python 的列表中反转某些元组(用户按列表索引输入)?

如何在python中将文件读取到列表中?

在python中从文本文件读取元组列表