Python数组奇怪的行为? [英] Python array strange behavior?

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

问题描述

谁能解释为什么会这样?

案例 1:

<预><代码>>>>a = [[0]] *3>>>打印一个[[0], [0], [0]]>>>a[1].append(0)>>>打印一个[[0, 0], [0, 0], [0, 0]]

情况 2:

<预><代码>>>>a = [[0],[0],[0]]>>>打印一个[[0], [0], [0]]>>>a[1].append(0)>>>打印一个[[0], [0, 0], [0]]

为什么会这样?我期待案例 1 中数组的行为与案例 2 中的一样,但这不是出于某种原因.

解决方案

在第一种情况下,您正在创建一个列表 [0] 并将其复制 3 次.这是同一个对象重复了 3 次.你应该只对不可变类型使用星形

为避免在您拥有可变类型时出现此问题,请使用列表推导式:

a = [[0] for _ in range(3)]

Can anyone explain why is this happening?

Case 1:

>>> a = [[0]] *3
>>> print a
[[0], [0], [0]]
>>> a[1].append(0)
>>> print a
[[0, 0], [0, 0], [0, 0]]

Case 2:

>>> a = [[0],[0],[0]]
>>> print a
[[0], [0], [0]]
>>> a[1].append(0)
>>> print a
[[0], [0, 0], [0]]

Why is this going on? I am expecting that the behavior of the array in case 1 to be as in case 2 but it is not for some reason.

解决方案

In the first case, you are creating a list [0] and duplicate it 3 times. This is the same object repeated three times. You should use the star form only with immutable type

To avoid this issue when you have a mutable type, use list comprehension:

a = [[0] for _ in range(3)]

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

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