在Python中解引用列表中的列表 [英] Dereferencing lists inside list in Python

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

问题描述

当我以通用"方式定义列表时:

When I define a list in a "generic" way:

>>>a=[[]]*3
>>>a
[[],[],[]]

,然后尝试仅附加到外部列表的第二个元素:

and then try to append only to the second element of the outer list:

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

如上所示,

它会附加到外部列表的所有元素上,这可能是由于这些元素是对同一列表的引用,而不是对不同列表的引用(为什么这样工作?).我如何实际以相同的泛型"方式创建列表,以使内部列表是不同的列表,而不仅仅是引用.谢谢.

it appends to all elements of the outer list as can be seen above, probably due to the fact that the elements are references to the same list and not different lists (why does it work that way?). How can I actually create a list in the same "generic" way, such that the inner lists would be different lists and not just references. Thanks.

推荐答案

您是正确的,它们都是对一个列表的引用.

You are correct, they are all references to one list.

[[] for _ in range(3)]

是创建独立空白列表的常用方法.您可以在Python 2.x上使用xrange,但是如果长度实际上与示例中的一样小,则不会有什么区别.

is a common way to create a list of independent empty lists. You can use xrange on Python 2.x, but it won't make a difference if the length is actually as small as in your example.

不确定如何解释原因(原因是它是通过这种方式实现的),但是您可以看到(至少是顺便记录了)此行为(

Not sure how to explain the reason for this (the reason is that it's implemented this way), but you can see that this behavior is documented (at least in passing) here:

Operation       Result                              Notes
s * n, n * s    n shallow copies of s concatenated  (2)

这里的浅"一词的确切含义是:这些元素是通过引用复制的.链接页面上的注2"也回答了您的问题.

The word "shallow" here means exactly that: the elements are copied by reference. "Note 2" at the linked page also answers your question.

这篇关于在Python中解引用列表中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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