【问题标题】:How to print the highest score on an external csv file如何在外部 csv 文件上打印最高分
【发布时间】:2022-11-27 01:26:45
【问题描述】:

我创建了一个小的顶级王牌游戏,并有一个 csv 文件,用于存储以前游戏的所有分数。我如何让它打印最高分?

field_names = ['player_name','score']

data = [{"player_name": player_name, 'score': score}]
with open("score.csv", "a") as csv_file:
    spreadsheet = csv.DictWriter(csv_file, fieldnames=field_names)
    spreadsheet.writerows(data)
with open('score.csv', 'r') as csv_file:
    spreadsheet = csv.DictReader(csv_file)
    for row in spreadsheet:
        print(dict(row))

【问题讨论】:

  • 使用熊猫包..
  • @DataFace 对这么简单的问题有很重的依赖。

标签: python csv


【解决方案1】:

创建一个变量来记住最高分,并将其初始化为零。

逐行读取 csv 文件。如果您看到比之前最高分更高的分数,请将其记为新的最高分。

在循环结束时,打印最高分。

# initialize to a placeholder value
highest_score = 0

# read the csv file
with open('score.csv', 'r') as csv_file:
    spreadsheet = csv.DictReader(csv_file)
    for row in spreadsheet:
        # convert the score column to an integer
        intscore = int(row['score'])

        # if this score is the highest so far, remember it
        if intscore > highest_score:
            highest_score = intscore

print(highest_score)

【讨论】:

    猜你喜欢
    • 2017-02-08
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2021-01-06
    相关资源
    最近更新 更多