我的代码解析输入文件(示例见下文)并将信息存储在列表/字典的组合中时遇到问题。
我有一个 CSV 文件,其中包含与此类似的行(它们是棒球统计数据):
Reyes,Jose,Mets,SS,681,191,36,12,12,57,.280
我现在可以拆分每个字段并将其正确存储在变量中,但是当我必须将数据存储在数据结构中时,问题就出现了。
我必须存储每个球员的统计数据,然后将球员存储在他们所属的每个球队的字典/列表中。
我的过程与此类似:
DICT OF TEAMS (TEAM IS KEY, VALUE IS A DICT OF PLAYERS)
|
V
DICT OF PLAYERS (THEIR FULL NAME IS KEY, VALUE IS A LIST OF STATS)
|
V
LIST OF STATS (EVERY SINGLE STAT IS IN HERE)
不幸的是,我的统计信息列表将填满整个文本文件中的信息(本质上是将文本文件放入列表中)。我尝试在 while 循环结束时清除表格,但即使我将列表存储在播放器字典中,它也会完全清除列表。
也许有人可以简化我的想法或告诉我我做错了什么。
这是我的代码供参考:
import sys
from collections import OrderedDict
if len(sys.argv) == 1:
filename = raw_input("No filename supplied. Please enter one now: ")
print "Filename supplied. Running now."
else:
print "Filename supplied. Running now."
filename = sys.argv[-1]
#print "\n"
f = open(filename, "r")
l = f.readline()
lastName = "" #0
firstName = "" #1
teamName = "" #2
position = "" #3
atBats = "" #4
baseHits = "" #5
doubles = "" #6
triples = "" #7
homeruns = "" #8
rbi = "" #9
batingAvg = "" #10
fullName = ""
teams = {}
players = {}
stats = []
while l:
l = l.strip("\n")
curCol = l.split(",")
l = f.readline()
lastName = curCol[0]
firstName = curCol[1]
teamName = curCol[2]
position = curCol[3]
atBats = curCol[4]
baseHits = curCol[5]
doubles = curCol[6]
triples = curCol[7]
homeruns = curCol[8]
rbi = curCol[9]
batingAvg = curCol[10]
fullName = firstName + " " + lastName
stats.append(lastName)
stats.append(firstName)
stats.append(teamName)
stats.append(position)
stats.append(atBats)
stats.append(baseHits)
stats.append(doubles)
stats.append(triples)
stats.append(homeruns)
stats.append(rbi)
stats.append(batingAvg)
players[fullName] = stats
print players