查找csv文件中每行的最大值

我需要从每一行中找到最大值,并以特定格式显示信息。 CSV文件是

name    tribe   id  Score1  Score2  Score3  Score4

Aang    Normad  N321B   89  67  54  78

Gyatso  Omaticaya O111C 54  78  65  78

我需要的是输出,如

                  Highest score

    Aang          Score1

    Gyatso        Score2, Score 4

到目前为止,根据我所做的代码,我只能显示两个玩家的最高分数。但是,我不确定如何将结果链接到哪个得分(例如得分1,得分2)。我也不知道如何使结果出现两次,例如Gyatso。已在网上搜索指南,但大多数都与查找最多列或建议使用我尚未开始学习的大熊猫有关。初学者到python和编码一般所以目前正在努力解决这个问题。非常感谢一些帮助,谢谢

def display_avatar_top_elements():
    with open(filePath) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            user,tribe,id, *scores= row.values()
            if all(score.isdigit() for score in scores):
                max_score= max([int(score) for score in scores])
                print (max_score)

电流输出

89
78
0
投票

您可以使用列表推导来获取数组最大值的所有索引。试试这个:

def display_avatar_top_elements():
    with open(filePath) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            user,tribe,id, *scores= row.values()
            if all(score.isdigit() for score in scores):
                int_scores = [int(score) for score in scores]
                max_score_indexes = [i for i,score in enumerate(int_scores) if score==max(int_scores)]
                print(['Score' + str(index+1) for index in max_score_indexes])
0
投票

首先从行中取出得分字典,然后获取最大键和值。

import csv
import operator
scores_list = []
with open('name.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        #Get the dictionary with all the scores
        scores = {k:v for k,v in row.items() if 'Score' in k}
        #Calculate the maximum score on value and append it to a list
        max_scores = list(max(scores.items(), key=operator.itemgetter(1)))
        scores_list.append(max_scores)
print(scores_list)

输出将是。

[
['Score1', '89'], 
['Score2', '78']
]
0
投票

尝试:

for row in reader:
    max_score = max(((sname, int(s)) for sname, s in row.items() if sname.startswith("Score")), key=lambda s: s[-1])
    print(max_score)