JacobA
JacobA

Reputation: 25

TypeError - Issue appending items to list

I am reading data from an input file containing MLB player stats. Each line of the file contains 9 elements relating to each player. I'm trying to calculate a few statistics and add them to the end of the list created with the player stats but am getting a type error specifying float object is not iterable. Here is the code I'm using to populate the list from the input file:

def readInput(fileName):
    stats = []
    try:
        fh = open(fileName, "r")
        #populated the stats list
        for 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 the same function, I've included the following code to calculate the desired statistics and add them to the 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 I receive this message: TypeError: 'float' object is not iterable.

Any advice or insight is greatly appreciated.

Upvotes: 0

Views: 55

Answers (2)

pcurry
pcurry

Reputation: 1414

I would suggest you break reading the file into one function, and calculating the stats into another function. That way you can test the functions separately, and you can reuse them separately.

It looks like you are trying to add battingAvg and sluggingAvg stats to the numbers you already have for each player.

More idiomatic Python would also be to use list comprehensions and context managers.

def readInput(fileName):
    try:
        with open(fileName, "r") as fh:
            list_of_players = [line.strip('\n').split(';') for 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):
    for 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

Upvotes: 0

bosnjak
bosnjak

Reputation: 8624

Although this is not the cause of your original issue, you are appending the stats while iterating over them. And you are appending them with battingAvg which is definitely not iterable.

for k in stats:
    atBats = k[3]  # at one point k is battingAvg, can't index that
    ...
    battingAvg = int(hits) / int(atBats)
    ...
    stats.append(battingAvg)
    ...
return stats

Update:

By the stack trace you sent in the comments:

Traceback (most recent call last): File "final.py", line 207, in main() File "final.py", line 169, in main stats = readInput(fileName) File "final.py", line 55, in readInput stats.extend(battingAvg) TypeError: 'float' object is not iterable

it seems that the code you posted in your question doesn't contain the relevant part. Basically, you are using extend() for a non-iterable element (float) - use append() to add it to the list.

This is because extend takes all the elements from one list, and appends it to a second list. And since there are no elements in float, you get the not iterable exception.

Upvotes: 2

Related Questions