查找csv fi中每行的最大值

2024-04-20 07:18:34 发布

您现在位置: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

Tags: csvfile代码inidfor分数maxreader
3条回答

尝试:

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)

首先从行中取出分数字典,然后获取最大键和值。你知道吗

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']
]

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

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])

相关问题 更多 >