我正在从包含MLB玩家统计数据的输入文件中读取数据。该文件的每一行包含与每个玩家相关的9个元素。我尝试计算一些统计信息并将其添加到使用播放器统计信息创建的列表的末尾,但是我收到了指定float object is not iterable
的类型错误。以下是我用来填充输入文件列表的代码:
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")
在同一个功能中,我已经包含以下代码来计算所需的统计数据并将其添加到stats
列表中:
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
然后我收到此消息:TypeError: 'float' object is not iterable
。
非常感谢任何建议或见解。
答案 0 :(得分:2)
虽然这不是原始问题的原因,但您在迭代它们时会附加统计信息。而且你用battingAvg
追加它们,这绝对不是可迭代的。
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
通过评论中发送的堆栈跟踪:
回溯(最近一次呼叫最后):文件" final.py",207行,in main()文件" final.py",第169行,在主stats = readInput(fileName)File" final.py",第55行,在readInput中 stats.extend(battingAvg)TypeError:' float'对象不可迭代
您在问题中发布的代码似乎并未包含相关部分。基本上,您使用extend()
作为非可迭代元素(float) - 使用append()
将其添加到列表中。
这是因为extend
从一个列表中获取所有元素,并将其附加到第二个列表。由于float
中没有元素,因此您将获得不可迭代的异常。
答案 1 :(得分:0)
我建议你将文件读入一个函数,并将统计数据计算到另一个函数中。这样您就可以单独测试这些功能,并且可以单独重复使用它们。
看起来你正在尝试将battingAvg和sluggingAvg统计数据添加到你已经拥有的每个玩家的数字中。
更多惯用Python也将使用列表推导和上下文管理器。
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