将项目附加到列表列表中的指定列表(Python)列表、项目、列表中、Python

2023-09-07 02:32:46 作者:六字女生大全:薄荷糖′微微凉

我目前正在通过解决来自项目 euler 的问题来练习我的编程技能,现在我在 Python 上遇到了一些(在我看来)奇怪的行为.

I'm practicing my progamming skills by solving problems from project euler at the moment, and now I've come across some (in my opinion) strange behavior on Python.

当我这样做时:

list = [[1]]*20

正如预期的那样,我得到了一个包含元素 1 的 20 个列表的列表.但是,当我想将 2 附加到此列表中的第三个元素时,我会这样做:

I get a list of 20 lists containing element 1, as expected. However, when I would like to append a 2 to the third element from this list, I would do that as follows:

list[3].append(2)

然而,这会改变列表中的所有元素.即使我绕道而行,比如:

This however changes ALL the elements in the list. Even when I take a detour, like:

l = list[3]
l.append(2)
list[3] = l

我所有的元素都变了.谁能告诉我如何执行此操作并获得如下输出:

All my elements get changed. Can anyone please tell me how to do this and get an output like so:

[[1], [1], [1], [1, 2], [1] .... [1]]

提前致谢.

推荐答案

Python 列表是可变对象,所以当您执行 [[1]]*20 时,它会创建 one 列出对象[1],然后在顶层列表中放置20个对它的引用.

Python lists are mutable objects, so when you do [[1]]*20 it creates one list object [1] and then places 20 references to it in the toplevel list.

就可变性问题而言,和下面是一样的

As far as the mutability problem is concerned, this is the same as the following

a = [1,2,3]
b = a
b.append(4)
a # [1,2,3,4]

这是因为 b=a 只是将 reference 从 a 复制到 b 的列表实例.它们都指的是同一个实际列表.

This happens because b=a merely copies the reference to the list instance from a to b. They are both referring to the same actual list.

为了创建列表列表,就像您在上面尝试的那样,您需要为每个条目创建一个唯一列表.列表推导效果很好:

In order to create a list of lists, like you tried above, you need to create a unique list for each entry. A list comprehension works nicely:

mainlist = [[1] for x in range(20)]
mainlist[0].append(2)
mainlist # [[1,2],[1],[1],...]

编辑

顺便说一句,由于类型名称是 Python 中的元类,因此使用类型名称命名变量是个坏主意.原因是这可能会导致代码中出现一些问题:

As an aside, since type names are metaclasses in Python, naming your variables by the type name is a bad idea. The reason is that can cause several issues further down in the code:

a = range(3) # [0,1,2]
type(a) # (type 'list')
isinstance(a, list) # True

现在,创建一个名为 list

list = range(3)
list # [0,1,2]
isinstance(list, list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

更不用说,现在你不能使用 list() 操作符

Not to mention, now you cant use the list() operator

c = list((1,2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable