在循环中的每次迭代开始时将变量重新分配给原始值(在循环之前定义) [英] Reassign variable to original value (defined prior to the loop) at start of each iteration in loop
问题描述
在Python中,在每次迭代开始时将变量重新分配给原始值(在循环之前定义)时,使用 [:]
。也就是说:
In Python, you use [:]
when reassigning a variable to an original value (defined prior to the loop) at the start of each iteration. That is to say:
original_1D = ['o', 'o', 'o']
for i in range(0,3):
new = original_1D[:] # revert back to 'original_1D' list defined before loop
new[i] = 'X'
print new
产生期望和预期的输出:
produces output that is both desired and expected:
['X', 'o', 'o']
['o', 'X', 'o']
['o', 'o', 'X']
如果原始列表是多维的,我的问题就出现了( original_2D
)。例如:
My issue arises if the original list is multi-dimensional (original_2D
). For example:
original_2D = [['o', 'o', 'o'],['o', 'o', 'o']]
for i in range(0,3):
new = original_2D[:] # revert back to 'original_2D' list defined before loop
new[0][i] = 'X'
print new
从此,我想要以下内容输出:
From this, I want the following output:
# Desired
[['X', 'o', 'o'], ['o', 'o', 'o']]
[['o', 'X', 'o'], ['o', 'o', 'o']]
[['o', 'o', 'X'], ['o', 'o', 'o']]
但没有!我明白了:
# Actual
[['X', 'o', 'o'], ['o', 'o', 'o']]
[['X', 'X', 'o'], ['o', 'o', 'o']]
[['X', 'X', 'X'], ['o', 'o', 'o']]
好像每次迭代都会覆盖 original_2D
列表。
as if the original_2D
list gets overwritten which each iteration.
我是什么做错了?
推荐答案
在Python中,你使用
[:]
将变量重新分配给原始值时
In Python, you use
[:]
when reassigning a variable to an original value
不,您使用它来创建一个全长切片(即浅拷贝) buffer-xrangerel =nofollow>序列。如果原始值是不可变序列(例如字符串和元组),则不需要,如果原始值不是序列则不起作用。
No, you use it to create a full-length slice (i.e. shallow copy) of a sequence. If the original value is an immutable sequence (e.g. strings and tuples) it's unnecessary, and if the original value isn't a sequence it won't work.
注意我在上面强调了浅拷贝 - 切片创建的新对象包含对与原始相同对象的引用。如果原始序列包含对可变对象的引用(例如,列表),则这可能是一个问题。
Note that I have emphasised shallow copy above - the new object created by the slice contains references to the same objects as the original. If your original sequence contains references to mutable objects (like, for example, lists), this can be a problem.
使用 copy.deepcopy
创建深层(而不是浅层)副本:
Either use copy.deepcopy
to create a deep (rather than shallow) copy:
from copy import deepcopy
new = deepcopy(original2D)
或显式创建子列表的浅拷贝,使用例如列表理解:
or explicitly create shallow copies of the sub-lists too, using e.g. a list comprehension:
new = [row[:] for row in original2D]
前者更容易扩展到更高的维度。
The former scales more easily to higher dimensions.
这篇关于在循环中的每次迭代开始时将变量重新分配给原始值(在循环之前定义)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!