The python empty dictionary list has different effects on the assignment.

Source: Internet
Author: User

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 !!!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.