如何循环文本文件 [英] How to loop through a text file
本文介绍了如何循环文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含文本文件的程序,我想要做的就是获取数据并打印出来。然而,当我看到我的击球avergae时,它只抓住第一个平均值而不是最高击球率
I have a program that has a text file and what I am trying to do is grab the data and print it. However, when I look at my batting avergae, it is only grabbing the first average not the highest batting average
ef getLists():
# Create a Variable to ask the user to get the file
fname = input("Enter the name of the MLB stats data file: ")
infile = open(fname, 'r')
# Creates lists for the text file
players = []
teams = []
positions = []
runs = []
hits = []
homeruns = []
averages = []
line = infile.readline()
for line in infile:
line = line.strip()
player, team, position, run, hit, homerun, average = line.split(',')
players = players + [player]
teams = teams + [team]
positions = positions + [position]
runs = runs + [run]
hits = hits + [int(hit)]
homeruns = homeruns + [int(homerun)]
averages = averages + [float(average)]
return players, teams, positions, runs, hits, homeruns, averages
# Find's the player with the highest average
def getHighestAverage(players, averages):
highestAverage = 0
for i in range(len(averages)):
if highestAverage >= averages[i]:
highestAverage = [i]
print(players[highestAverage],averages[highestAverage])
推荐答案
您正在混淆值和索引。使用
You are confusing the value and the index. Use
if highestAverage >= averages[i]:
highestIndex= i
highestAverage= averages[i]
print(players[highestIndex], averages[highestIndex])
这篇关于如何循环文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文