python中的奇怪二维列表行为 [英] Strange 2 dimensional list behaviour in python

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

问题描述

python为什么要执行以下操作?

Why does python do the following?

>>> bla = [[]] * 5
>>> bla[3].append("blub")
>>> print bla
[['blub'], ['blub'], ['blub'], ['blub'], ['blub']]

我希望

[[], [], [], ['blub'], []]

推荐答案

与隐式传递引用有关,这是Python的常见混淆点.当您键入

This is a common point of confusion with Python, to do with the implicit pass-by-reference. When you type

x = []

绑定名称x

指向内存中的空列表.

that binds the name x to point to an empty list in memory. When you do

x = [[]] * 5

绑定名称x

指向一个由五样东西组成的列表,每个东西都是对 same 空列表的引用.如果您这样看,可能会更清楚:

that binds the name x to point to a list of five things, each one of which is a reference to the same empty list. This might be clearer if you think of it like this:

>>> y = []
>>> x = [y]*5
>>> x
[[], [], [], [], []]
>>> x[0].append(0)
>>> x
[[0], [0], [0], [0], [0]]
>>> y
[0]

也就是说,即使[]不绑定任何变量名,它仍然会创建对空列表的引用,然后将其复制5次.

That is, even though [] doesn't bind any variable names, it still creates a reference to an empty list, which is then copied five times.

如果您不希望这样做,则需要显式构造五个空列表以存储在x中.有多种方法可以做到这一点(copy.deepcopy是一般解决方案),但我认为最容易做到的是:

If you don't want this, you need explicitly to construct five empty lists to store in x. There are various ways of doing this (copy.deepcopy is a general solution), but I think the neatest is:

x = [[] for _ in range(5)]

或者,numpy是一个扩展模块,提供了非常强大的多维数组.

Alternatively, numpy is an extension module which provides a very powerful multidimensional array.

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

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