我试图用非常相似的数据读取多个文件。此数据的每一行都有一个accessor_key和一个与它相关联的值。我正在尝试创建一个字典,它以accessor_key作为字典键和字典值--到目前为止读取的所有值的列表。
我的代码如下所示:
with open(ind_file, "r") as r:
for line in r:
nline = line.strip()
spl = nline.split(",")
if agg_d.has_key(spl[0]):
key = spl[0]
val = spl[1]
dummy = agg_d[key]
dummy.append(val)
agg_d[key] = dummy
print key, agg_d[key]
else:
print "Something is wrong"
print agg_d
print spl[0]
print spl[1]正如您所看到的,我希望值每次都变大(列表的大小每次增加1次),并将其存储回字典中。但是,当我运行这个程序时,字典中的所有键都会接受列表的值。
例如,在程序的开头,字典是:
agg_d = {'some_key': [], 'another_key': []}在运行它之后,一旦它变成:
agg_d = {'some_key': ['1'], 'another_key': ['1']}当它应该是公正的:
agg_d = {'some_key': ['1'], 'another_key': []}编辑:我找到了我要找的工作。我只是做了:
with open(ind_file, "r") as r:
for line in r:
nline = line.strip()
spl = nline.split(",")
if agg_d.has_key(spl[0]):
key = spl[0]
val = spl[1]
dummy = agg_d[key]
ad = dummy[:]
ad.append(val)
agg_d[key] = ad
print key, agg_d[key]
else:
print "Something is wrong"
print agg_d
print spl[0]
print spl[1]但我还是想知道为什么会发生这种事。“虚拟”是指字典中的所有值吗?我是用Python2.7运行这个的。
发布于 2016-02-04 03:36:39
看起来agg_d已经用您期望的密钥初始化了。您没有说明这是如何完成的,但我猜想所有的初始值实际上都是相同的列表--您在上面的代码中添加了值。
如果您用新的每个键列表初始化agg_d,那么问题就会消失。你也许可以通过一本字典的理解来做到这一点:
>>> keys = ["a", "b", "c"]
>>> agg_d = {k:[] for k in keys}
>>> agg_d["a"].append(1)
>>> agg_d
{'a': [1], 'c': [], 'b': []}或者,根据您的需要,您可以在读取文件时遇到每个键时,根据需要初始化每个条目。
您的解决方案之所以有效,是因为它用新列表替换了原始列表,并删除了共享引用。
发布于 2016-02-04 03:33:49
“虚拟”是指字典中的所有值吗?我是用Python2.7运行这个的。
是。您已经添加了对列表的引用,并且可以像您观察到的那样对该列表进行多个引用。为了简单地说明这一点,请尝试如下:
dummy = [1,2,3] # creates a list object and assigns reference to the name 'dummy'
d = dict()
d['some key'] = dummy # creates the key 'some key' in the dictionary and assigns its value as the reference to the name 'dummy'
dummy.append(4) # mutates the list referred to by name 'dummy'
# at this point, all references to that object have mutated similarly
print d['some key']您将看到以下输出:
>>> [1,2,3,4]您的解决方法是可以的,但是您可以改进:
with open(ind_file, "r") as r:
for line in r:
spl = line.strip().split(",")
key, val = spl[0], spl[1]
if key in agg_d:
agg_d[key] = agg_d[key][:].append(val)
print key, agg_d[key]
else:
print "Something is wrong"
print agg_d
print spl[0]
print spl[1]
agg_d[key] = agg_d[key][:].append(val)这不会改变您的dummy列表,并将值重新分配到字典。还避免了一些不必要的变量,如nline、ad和dummy。
发布于 2016-02-04 03:34:07
问题是,默认情况下,Python只是将对列表的引用添加为dict值,而不是列表本身。所以dict值实际上是指向同一个对象的一串指针。您需要按照注释中的建议使用虚拟的方式显式地复制列表,或者使用copy.deepcopy()更显式地复制列表。
https://stackoverflow.com/questions/35191919
复制相似问题