将项目附加到列表列表中的指定列表 (Python) [英] Append item to a specified list in a list of lists (Python)

查看:34
本文介绍了将项目附加到列表列表中的指定列表 (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在通过解决 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 只是将referencea 复制到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

这篇关于将项目附加到列表列表中的指定列表 (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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