i reading data input file containing mlb player stats. each line of file contains 9 elements relating each player. i'm trying calculate few statistics , add them end of list created player stats getting type error specifying float object not iterable
. here code i'm using populate list input file:
def readinput(filename): stats = [] try: fh = open(filename, "r") #populated stats list line in fh: line = line.strip('\n') allplayers = line.split(";") stats.append(allplayers) print("player data has been loaded\n") fh.close() except: print("file not found")
in same function, i've included following code calculate desired statistics , add them stats
list:
for k in stats: atbats = k[3] hits = k[5] doubles = k[6] triples = k[7] homeruns = k[8] singles = int(hits) - (int(doubles) + int(triples) + int(homeruns)) totalbases = int(singles) + (2 * int(doubles)) + (3 * int(triples)) + (4 * int(homeruns)) battingavg = int(hits) / int(atbats) sluggingpct = int(totalbases) / int(atbats) print(battingavg) print(sluggingpct) stats.append(battingavg) stats.append(sluggingpct) return stats
then receive message: typeerror: 'float' object not iterable
.
any advice or insight appreciated.
i suggest break reading file 1 function, , calculating stats function. way can test functions separately, , can reuse them separately.
it looks trying add battingavg , sluggingavg stats numbers have each player.
more idiomatic python use list comprehensions , context managers.
def readinput(filename): try: open(filename, "r") fh: list_of_players = [line.strip('\n').split(';') line in fh] print("player data has been loaded\n") return list_of_players except ioerror: print("file not found") def calculate_player_stats(player): atbats = float(player[3]) hits = int(player[5]) doubles = int(player[6]) triples = int(player[7]) homeruns = int(player[8]) multibase_hits = sum((doubles, triples, homeruns)) singles = hits - multibase_hits totalbases = singles + (2 * doubles) + (3 * triples) + (4 * homeruns) # or total_bases = hits + doubles + homeruns + 2 * (triples + homeruns) battingavg = hits / atbats sluggingpct = totalbases / atbats print(battingavg) print(sluggingpct) player.append(battingavg) player.append(sluggingpct) def calculatestats(list_of_players): player in list_of_players: calculate_player_stats(player) list_of_players = readinput(filename) if list_of_players: calculatestats(list_of_players) return list_of_players