Python The appended element in the list changes as its original variable changes

前端 未结 1 383
说谎
说谎 2020-12-02 02:24

So here\'s the abstract code of what I\'m trying to do in python.

list_ = []
dict_ = {}
for i in range(something):
    get_values_into_dict(dict_)
    list_.         


        
相关标签:
1条回答
  • 2020-12-02 03:00

    You are adding a reference to the dictionary to your list, then clear the dictionary itself. That removes the contents of the dictionary, so all references to that dictionary will show that it is now empty.

    Compare that with creating two variables that point to the same dictionary:

    >>> a = {'foo': 'bar'}
    >>> b = a
    >>> b
    {'foo': 'bar'}
    >>> a.clear()
    >>> b
    {}
    

    Dictionaries are mutable; you change the object itself.

    Create a new dictionary in the loop instead of clearing and reusing one:

    list_ = []
    for i in range(something):
        dict_ = {}
        get_values_into_dict(dict_)
        list_.append(dict_)
    print list_
    

    or better still, have get_values_into_dict() return a dictionary instead:

    list_ = []
    for i in range(something):
        dict_ = return_values_as_dict()
        list_.append(dict_)
    print list_
    
    0 讨论(0)
提交回复
热议问题