[英]Finding sum of rows from CSV files with header
需要在用戶輸入玩家ID時找到用戶的平均分數
.csv 文件:
名稱部落 id Score1 Score2 Score3 Score4
Aang Normad N321B 89 67 54 78Gyatso Omaticay O111C 54 78 65 54
我嘗試添加一些我在 SO 上找到的東西,但得到了錯誤:int() 的無效文字,基數為 10:'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')
您的錯誤准確地告訴您問題是什么。 您的代碼試圖在這一行中將標頭標簽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']
您需要為不存在的鍵添加額外的檢查並刪除 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.