weird behaviour with list of dictionaries in python

前端 未结 2 948
春和景丽
春和景丽 2021-01-22 11:59

Here is a simple code that performs operations on lists:

>>> a = [0] * 5
>>> a
[0, 0, 0, 0, 0]
>>> a[0] = 5
>>> a
[5, 0, 0, 0         


        
相关标签:
2条回答
  • 2021-01-22 12:26

    This is not weird.


    Workaround:

    a = [{} for i in xrange(5)]
    

    […] * 5 creates one and a list of five pointers to this .

    0 is an immutable integer. You cannot modify it, you can just replace it with another integer (such as a[0] = 5). Then it is a different integer.

    {} is a mutable dictionary. You are modifying it: a[0]['b'] = 4. It is always the same dictionary.

    0 讨论(0)
  • 2021-01-22 12:39

    Try this,

    a = map([].append, {} for i in xrange(3))
    
    0 讨论(0)
提交回复
热议问题