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

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

问题描述

谁能解释为什么会这样?

Can anyone explain why is this happening?

情况1:

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

情况2:

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

为什么会这样?我希望情况1的数组的行为与情况2的一样,但这不是出于某种原因.

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.

推荐答案

在第一种情况下,您将创建列表[0]并将其重复3次.这是同一对象重复三次.您应仅将星形形式与不可变类型一起使用

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天全站免登陆