python中列表的奇怪行为 [英] Strange behavior of lists in python

查看:49
本文介绍了python中列表的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
Python 列表问题

我不明白 Python 中列表的行为:

<预><代码>>>>a1 = [[0,0],[0,0]]>>>a2 = [[0]*2]*2>>>a1[[0, 0], [0, 0]]>>>a2[[0, 0], [0, 0]]>>>a1[0][0] = 1>>>a2[0][0] = 1>>>a1[[1, 0], [0, 0]]>>>a2[[1, 0], [1, 0]]

为什么一个元素的赋值会影响另一个元素?谢谢解答!

解决方案

当您乘以一个列表时,它会复制对列表的引用,而不是创建列表的副本.由于列表是可变的,当你改变它时,它的所有引用都会改变.

在 ASCII 艺术术语中:

a1 --- [list1, list2] --- list1 = [0, 0]--- list2 = [0, 0]a2 --- [list3, list3] --- list3 = [0, 0]

您可以清楚地看到更改 list3 会影响两个位置.

如果你想在不复制引用的情况下创建可变长度的列表,你应该这样做:

<预><代码>>>>a2 = [[0]*2 for _ in range(2)]>>>a2[0][0] = 1>>>a2[[1, 0], [0, 0]]

这里我们使用 列表理解,以便每次都创建新元素,而不是复制对旧元素的引用.在更复杂的情况下,如果您有想要重复的现有可变对象,您可能需要使用 <代码>复制模块.

注意 [0]*2 操作还是可以的,因为 Python 中的 int 是不可变的,不能改变,所以没关系你有对同一个对象的引用.

Possible Duplicate:
Python list problem

I don't understand behavior of lists in python:

>>> a1 = [[0,0],[0,0]]
>>> a2 = [[0]*2]*2
>>> a1
[[0, 0], [0, 0]]
>>> a2
[[0, 0], [0, 0]]
>>> a1[0][0] = 1
>>> a2[0][0] = 1
>>> a1
[[1, 0], [0, 0]]
>>> a2
[[1, 0], [1, 0]]

Why assignment of one element affects to another element? Thanks for answers!

解决方案

When you multiply a list, it copies a reference to the list, it doesn't create a copy of the list. As lists are mutable, when you change it, it is changed for all the references to it.

In ASCII-art terms:

a1 --- [list1, list2] --- list1 = [0, 0]
                      --- list2 = [0, 0]

a2 --- [list3, list3] --- list3 = [0, 0]

You can clearly see that changing list3 will affect both positions.

If you want to create variable-length lists without copying references, you should instead do something like this:

>>> a2 = [[0]*2 for _ in range(2)]
>>> a2[0][0] = 1
>>> a2
[[1, 0], [0, 0]]

Here we are using a list comprehension in order to create new elements each time, rather than copying references to old elements. In more complex situations, where you have existing mutable objects you want to repeat, you might want to use the copy module.

Note the [0]*2 operation is still OK, as ints in Python are immutable, and can't change, so it doesn't matter if you have references to the same object.

这篇关于python中列表的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆