I need to create a list of lists in Python, so I typed the following:
< Code> MyList = [[1] * 4] * 3
The list looks like this:
[[1, 1, 1, 1] , [1, 1, 1, 1], [1, 1, 1, 1]]
Then I changed one of the lowest values:
[[5, 1, 1, 2] 1], [5, 1, 1, 1], [5, 1, 1, 1]]
What I wanted or was not expected could anyone understand this Whether that Is and how to get around it?
When you must [X] * 3
Get the code> [x, x, x] . That is, a list with 3 references of the same x
when you modify this single x
, it appears through three contexts.
To fix this, you need to make sure that you create a new list in each case. One way to do this
[4] (3) for n for category [[]]
multiplier operator *
is running on objects, without seeing expression When you use *
to multiply [[1] * 4] by [3],
, no *
, then only 1-element The list evaluates [code] [[1] * 4] [[1] * 4
expression text *
does not know that How to make copies of the element, it is not known how to evaluate [[1] * 4]
again, and you do not want any copies, and in general, there is no need to copy the element There can be no way too.
The only option *
is to make new references to the current abbolist instead of trying to create new Upanishads; something else would be incompatible or to provide a fresh start to the design decisions of the original language Will be required.
On the contrary, the understanding of a list re-evaluates the element expression on each walk. [[1] * range for 4 (3)]
reevaluates [1] * 4
for every single reason [x ** 2x range] Every evaluation of
revalue [1] * 4
every time creates a new list in the (3)] x ** 2
, so understanding the list Who wants
Incidentally, [1] * 4
does not even copy the elements of [1]
, but it does not matter because Integers are irreversible. You can do nothing like 1.value = 2
and can change 2 in 1.
No comments:
Post a Comment