python - 循环运行后列表中的值发生变化

标签 python list loops

我最近一直在清理一些数据,只有一件事让我印象深刻。 简单的例子:

test_list1 = [[1,2,3,4,5], [1,2,3,4,5]]

for x in test_list1:
    for y in range(0, len(x)):
        x[y] = 0

print(test_list1)

-> [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

但是,如果我尝试以下操作,我会得到不同的结果:

test_list2 = [1,2,3,4,5]

for x in test_list2:
    x = 0

print(test_list2)

-> [1, 2, 3, 4, 5]

对我来说,在 test_list1 中,我能够更改其子列表中的值,而无需实际引用 test_list1,这似乎很奇怪。 如果我没有明确声明 test_list1[0][0] = 0 等,为什么 test_list1 中的值只是通过运行循环而改变? 在test_list2中,这是不可能的。

提前致谢

最佳答案

您的问题可以简化为:

a = 0
b = a
b = 1
print(a, b) # >> 0 1

a = [0,0]
b = a
b[0] = 1
print(a, b) # >> [1, 0] [1, 0]

这是因为当您对数字执行 b = a 时,ba 的副本,因此您可以单独编辑它们。但是当您使用列表执行此操作时,这两个变量对应于同一个对象。这样做主要是为了提高效率(每次执行诸如 a = b 之类的操作时都复制一个列表,效率非常低,而且通常毫无用处)。因此,当您编辑其中一个时,另一个会受到影响。

for x in test_list2: 中,xtest_list2 元素的副本。但在for x in test_list1:中,x直接对应于test_list2的一个元素(列表)。

更多详情,您可以阅读this article about mutable objects .

关于python - 循环运行后列表中的值发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53752520/

相关文章:

r - 如何在条件下将列表的所有元素与另一个数据表合并

java - 流式作业与循环批处理作业使用 Kafka 队列中的数据

python - keras中model.compile的参数 'weighted_metrics'和model.fit_generator的参数 'class_weight'之间的区别?

python - 无法解码 JSON 对象 - django - pythonanywhere

python 2个带索引的嵌套列表的并集

python - 从列表构造一个字典,其中每个值将包含当前键的补码

python - pip install numpy 的问题 - RuntimeError : Broken toolchain: cannot link a simple C program

python - 在 Python 中清除控制台

java - 无法正确计算Java中的二维数组

VBA : While loop not working with multiple (or) condtions