从带有head的CSV文件中查找行的总和

2024-05-15 03:11:46 发布

您现在位置:Python中文网/ 问答频道 /正文

当用户输入玩家id时,需要找到用户的平均得分

csv文件:

name tribe id Score1 Score2 Score3 Score4
Aang Normad N321B 89 67 54 78

Gyatso Omaticay O111C 54 78 65 54

我尝试添加在SO上找到的一些内容,但出现了错误:以10为基数的int()的文本无效:“Score1”。会很感激任何人能给我指出正确的方向,刚刚开始学习python。你知道吗

import  csv
filePath="data.csv"


with open(filePath) as csvfile:
    avatar_id=  input ("Enter Avatar ID:")    
    reader = csv.DictReader(csvfile)  
    for row in reader:
        if avatar_id in row['id']:
        #just print some stuff
            user,tribe,id, *scores= row 
            average= sum([int(score) for score in scores])/4
              print("{0:>6}{1:>8}{2:>7}{3:>7}{4:^14}".format(row['Air'],row['Water'],row['Earth'],row['Fire'], average))
            print("==============================") 
        else:
            x=5
if x>4:
    print('No avatar found')

Tags: csvcsvfile用户inidforifreader
3条回答

您需要为不存在的键添加额外的检查,并删除CSV文件中的空行。您还需要将分隔符添加到csv.DictReader文件因为它默认为逗号分隔符。参见下面的示例:

import  csv
import io
filePath="""name tribe id Score1 Score2 Score3 Score4
Aang Normad N321B 89 67 54 78
Gyatso Omaticay O111C 54 78 65 54
"""

avatar_id=  input ("Enter Avatar ID:")    
reader = csv.DictReader(io.StringIO(filePath),delimiter=' ')  
for row in reader:
    print(row)
    if avatar_id in row.get('id',''):
        user,tribe,id, *scores= row.values()
        average= sum([int(score) for score in scores])/4
        print("==============================") 
        break
    else:
        x=None
if x is None:
    print('No avatar found')
else:
    print("{} score is {}".format(avatar_id,x))

你的错误准确地告诉了你问题所在。您的代码正在尝试将标题标签Score1转换为此行中的整数:

average= sum([int(score) for score in scores])/4

失败了。为了避免在计算中包含头标签,请测试reader.line_num以跳过文件的第一行。你知道吗

或者,为了安全起见,忽略任何非数字数据:

if all(score.isdigit() for score in scores):
    average= sum([int(score) for score in scores])/4

替换

*scores= row

scores = row['Score1']+row['Score2']+row['Score3']+row['Score4']

相关问题 更多 >

    热门问题