1

我有这样的功能:

def main2():
    props = []
    prop_list = []
    i=0
    while (i < 10):
        new_prop = {
            'i': 1
        }
        props.append(new_prop)
        prop_list.append({'i': 1, 'props': props,})
        if i == 0:
            print prop_list
        i += 1
    print prop_list[0]

它输出这个:

[{'i': 1, 'props': [{'i': 1}]}]
{'i': 1, 'props': [{'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}]}

为什么最终打印与第一次打印不一样?当我追加一个新元素时,列表中先前添加的元素似乎正在更新。

4

2 回答 2

2

有了这条线,

prop_list.append({'i': 1, 'props': props,})

dict 包括 props列表对象。此列表在通过循环的后续迭代中发生变化:

props.append(new_prop)

打印的最终值prop_list[0]反映了这种变化。


这是孤立的同一件事:

In [23]: x = []

In [24]: y = {'foo': x}

In [25]: y
Out[25]: {'foo': []}

In [26]: z = {'baz': x}

In [27]: x.append('bar')    # x is mutated

In [28]: y                 
Out[28]: {'foo': ['bar']}   # both y and z are affected

In [29]: z
Out[29]: {'baz': ['bar']}

如果您不希望发生这种情况,请制作一份该列表的副本。要制作 的浅拷贝props,请使用props[:]

prop_list.append({'i': 1, 'props': props[:]})

请注意,浅拷贝props[:]一个新列表,其中包含与props. 这意味着如果props包含一个可变项(例如列表),则更改该列表会影响两者props及其浅表副本。

要(递归地)制作所有项目的深层副本,请使用props

import copy
prop_list.append({'i': 1, 'props': copy.deepcopy(props)})
于 2013-05-07T21:13:37.093 回答
1

在行

prop_list.append({'i': 1, 'props': props,})

props总是指同一个对象,在顶部初始化

props = []

并附加到循环的每次迭代中while

于 2013-05-07T21:13:52.187 回答