python - 存储列表字典的问题

标签 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

最佳答案

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

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:]

关于python - 存储列表字典的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19713310/

相关文章:

python - 如何在 python 中使用 ctypes 获取 Windows 窗口名称

python - 在 Google Keep 中对笔记进行排序 - gkeepapi

C# 6.0 列表出现语法错误, ' , '

Python glob——从列表中获取最新文件

c# - 如何优化使用 Dictionary<string, class> 的代码

python - Django REST 框架 : Basic Auth without debug

Python 命名约定——namedtuples

python - 从大小不均的列表列表中找到最大项

python - 在 Python 中使用字典作为集合中的项目

python - 从数据帧 python 创建自定义字典时出现字符串索引错误