在列出的清单项追加到指定列表(蟒蛇) [英] Append item to a specified list in a list of lists (Python)

查看:159
本文介绍了在列出的清单项追加到指定列表(蟒蛇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被此刻的解决从项目欧拉问题我练技能的预设电台,现在我已经遇到了一些(在我看来)怪异行为上的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 它创建< STRONG>有一个列表对象 [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 仅仅是拷贝的参考应用于列表实例C>到 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.

为了创建一个列表的列表,像你上面试过,你需要为每个条目的唯一列表。名单COM prehension很好地工作:

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中,通过类型名称命名变量是一个坏主意。
其原因是可能会导致几个问题在code进一步下跌:

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

现在,创建一个名为变量列表

Now, create a variable named 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()运营商

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

这篇关于在列出的清单项追加到指定列表(蟒蛇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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