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

时间:2019-04-26 09:24:48

标签: python

我需要从每一行中找到最大值,并以某种格式显示信息。 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

3 个答案:

答案 0 :(得分: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])

答案 1 :(得分: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']
]

答案 2 :(得分: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)