0

所以我有,

fo = {'current': [[1,23],[3,45],[5,65]]}
pl = {'current': [(2,30),(3,33),(5,34)]}

total = {}
for i in fo,pl:             
    for j in i:             
        if total.get(j):    
            total[j] += i[j]
        else:               
            total[j] = i[j]

所以,我预计,

total = {'current': [[1,23],[3,45],[5,65],(2,30),(3,33),(5,34)]}. 

我知道这是合并列表和元组。

But why does, fo =  {'current': [[1,23],[3,45],[5,65],(2,30),(3,33),(5,34)]} ??

有什么提示吗?合并列表和元组有问题吗?我认为,两者都是列表,列表是可变的,而元组不是。这是唯一的区别。

4

2 回答 2

1
fo = {'current': [[1,23],[3,45],[5,65]]}
pl = {'current': [(2,30),(3,33),(5,34)]}

total = {}
for i in fo,pl:             
    for j in i:             
        if total.get(j):    
            total[j] += i[j] # in this step you actually modified the  list fo['current']` 
                             # it is equivalent to fo['current'] += i[j]
        else:               
            total[j] = i[j]  # this step simply creates a new 
                             # reference to the list fo['current']

            print fo['current'] is total[j]
            #prints True as both point to the same object

一个快速的解决方法是将浅拷贝分配给total

total[j] = i[j][:]
于 2013-06-11T18:19:24.603 回答
1

这是因为您正在使用+=运算符。这会修改列表。在您的代码中,您最终会得到对fo['current']存储在total字典中的引用。当您修改它时total,列表fo也会看到修改,因为它们是同一个列表

在这种情况下,我可能会使用defaultdict

import collections
fo = {'current': [[1,23],[3,45],[5,65]]}
pl = {'current': [(2,30),(3,33),(5,34)]}
total = collections.defaultdict(list)
for d in fo,pl:
    for key in d:
        total[key].extend(d[key])

total.default_factory = None #allow KeyErrors to happen

print total # defaultdict(<type 'list'>, {'current': [[1, 23], [3, 45], [5, 65], (2, 30), (3, 33), (5, 34)]})
print fo  # {'current': [[1, 23], [3, 45], [5, 65]]}
print pl  # {'current': [(2, 30), (3, 33), (5, 34)]}
于 2013-06-11T18:13:07.953 回答