gpt4 book ai didi

python - 如何从外部文件中列出 python 中的数字?

转载 作者:行者123 更新时间:2023-11-30 23:37:45 24 4
gpt4 key购买 nike

外部文件的内容是这样的:

Ricky, 12
Sachin, 45
Brian, 2
Monty, 1

我基本上想做的是能够在 python 中阅读它并能够对其进行排序,因此它的分数最低在底部,最高分数在顶部。

这是我到目前为止得到的代码:

def SaveTopScores():
return HiScores.rsplit('(',1)[1]

with open("HiScores.txt", "r")as file:
HiScoreslist = HiScores.read().splitlines()

HiScoreslist.sort()

HiScoreslist.sort(key=HiScore)

for HiScore in HiScoreslist:
print(HiScore)

我仍然是 python 的新手,确实需要帮助。请纠正我错误的地方,并告诉我是否完全错误,如果是,我解决问题的最佳方法是什么?

最佳答案

一些列表理解:

with open("HiScores.txt") as hiscores:
scores = [line.split(',') for line in hiscores if line.strip()]
scores = [(name.strip(), int(score)) for name, score in scores]
scores.sort(key=lambda s: s[1], reversed=True)

for name, score in scores:
print('{:<20} {:>10}'.format(name, score))

这个:

  1. 作为上下文管理器打开文件(with ... as ...),因此它会自动关闭
  2. 循环遍历文件,分割每一行(前提是该行不为空)
  3. 将文件中的每个 2 值条目转换为剥离字符串和整数
  4. 根据每个元组中的第二个值(分数)对文件进行排序,并反转结果(最高分在前)
  5. 按格式打印每个条目(将每个名称在 20 个字符的区域中向左对齐,将每个分数在 10 个字符的字段中向右对齐)。

关于python - 如何从外部文件中列出 python 中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15201066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com