python追加和+ =与dict的问题

时间:2011-08-10 11:07:50

标签: python syntax

这似乎很简单,但我不知道我错了什么。

d1 = dict(zip(range(10), [[]]*10))
l1 = zip(range(10), range(10,20))

for pair in l1:
    d1[pair[0]].append(pair)

结果d1:

>>> d1
{0: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 1: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 2: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 3: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 4: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 5: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 6: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 7: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 8: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 9: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]}

用这个:

for pair in l1:
    d1[pair[0]] += [pair]

同样的事情,但是:

for pair in l1:
    d1[pair[0]] = d1[pair[0]] + [pair]

它给了我想要的结果

>>> d1
{0: [(0, 10)], 1: [(1, 11)], 2: [(2, 12)], 3: [(3, 13)], 4: [(4, 14)], 5: [(5, 15)], 6: [(6, 16)], 7: [(7, 17)], 8: [(8, 18)], 9: [(9, 19)]}

似乎我错过了语法中的基本内容,是否有人可以指出它? 感谢〜

亚历

2 个答案:

答案 0 :(得分:5)

不要对可变对象使用乘法。它为您提供了对象的X引用,而不是X个不同的对象。

d1 = dict((idx, []) for idx in range(10))

答案 1 :(得分:3)

而不是[[]]*10,您应该使用

[[] for i in range(10)]

因为第一个只是生成一个指向单个数组引用的元素列表。

实施例

>>> d1 = dict(zip(range(10), [[] for i in range(10)]))
>>> l1 = zip(range(10), range(10,20))
>>>
>>> for pair in l1:
...     d1[pair[0]].append(pair)
...
>>> d1
{0: [(0, 10)], 1: [(1, 11)], 2: [(2, 12)], 3: [(3, 13)], 4: [(4, 14)], 5: [(5, 1
5)], 6: [(6, 16)], 7: [(7, 17)], 8: [(8, 18)], 9: [(9, 19)]}
>>>
>>> d1
{0: [(0, 10)], 1: [(1, 11)], 2: [(2, 12)], 3: [(3, 13)], 4: [(4, 14)], 5: [(5, 1
5)], 6: [(6, 16)], 7: [(7, 17)], 8: [(8, 18)], 9: [(9, 19)]}