存储列表字典的问题

时间:2013-10-31 17:44:30

标签: python list dictionary

我的代码解析输入文件(下面看到的示例),并将信息存储在列表/词典的组合中。

我有一个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

1 个答案:

答案 0 :(得分:2)

我相信你必须在每次迭代结束时清除你的统计数据列表。

while l:
    # ...
    stats = []

编辑:

啊,我理解你的问题。这是因为当你将列表存储在字典中然后清除它时,它也会在字典中清除它。

我相信你可以复制一份列表来存储在字典中:

import copy
# ...
players[fullName] = copy.deepcopy(stats)
stats = []

编辑2:

或者,我相信你可以这样做

with open(filename, 'r') as f:
    for line in f:
        firstName = line.split(",")[0]
        lastName = line.split(",")[1]
        players[firstName + " " + lastName] = line.split(",")[2:]