所以,我有,
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)]} ??
任何提示?合并列表和元组是否有问题?我认为,列表和列表都是可变的,而元组则不是。这是唯一的区别。
答案 0 :(得分: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)]}
答案 1 :(得分: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][:]