The python empty dictionary list has different effects on the assignment.
Recently, Naive Bayes has encountered an interesting phenomenon (based on Python3.6.3)
I generate a list composed of 10 empty dictionaries:
FirstGeneration Method (most people may use this method, which is simple)
> A = [{}] * 10
However, a problem occurs when assigning values to the dictionary in.
> A [3] [3] = 32
>
[{3: 32 },
{3: 32 },
{3: 32 },
{3: 32 },
{3: 32 },
{3: 32 },
{3: 32 },
{3: 32 },
{3: 32 },
{3: 32 },
{3: 32 },
{3: 32}]
> A [4] [4] = 5
>
[{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5 },
{3: 32, 4: 5}]
We can find that for a [A] [B] = y, no matter what A is, this expression will add or modify field B for all dictionaries in.
HoweverSecondMethod (list generation)
> A = [{} for I in range (10)]
> A [3] [3] = 32
>
[{},{},{}, {3: 32 },{},{},{},{},{},{},{}]
> A [4] [4] = 5
>
[{},{},{}, {3: 32 },{ 4: 5 },{},{},{},{},{}]
We can find that for a [A] [B] = y, this expression can separately add or modify field B for the dictionary indexed as a in.
At that time, the empty dictionary list created in the first method was assigned a value and fell into the trap. The second problem is solved.
But I still don't know why there is such a difference. If you know anything, please leave a message below. Thank you !!!