更改列表列表中的项目 [英] changing an item in a list of lists

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

问题描述

可能重复:
关于双循环的简单python代码

Possible Duplicate:
Simple python code about double loop

我一直坚持在列表列表中更改一项的众所周知的问题.我需要使用固定大小的列表列表.

I'm stuck with the well known problem of changing 1 item in a list of lists. I need to use a fixed size list of list.

如果我使用:

In [21]: a=[[2]*2]*3

In [22]: a
Out[22]: [[2, 2], [2, 2], [2, 2]]

In [23]: a[0][0]=1

In [24]: a
Out[24]: [[1, 2], [1, 2], [1, 2]]

但是,如果我通过以下方式定义列表列表,它将起作用:

But if I define the list of list in the following way, it works:

In [26]: a = [
   ....: [2,2],
   ....: [2,2],
   ....: [2,2],
   ....: ]

In [27]: a   
Out[27]: [[2, 2], [2, 2], [2, 2]]

In [28]: a[0][0]=1

In [29]: a
Out[29]: [[1, 2], [2, 2], [2, 2]]

对我来说,第22行和第27行看起来相同.那有什么区别?

To me line 22 and 27 looks identical. So which is the difference?

有人可以向我解释如何解决此问题,尤其是如何更改用于更改列表列表中单个项的代码吗?如果不可能做到这一点,那么是否有建议改用其他数据结构呢? 谢谢

Can someone explain me how to go around this problem and, in particular, how to change a code that change a single item of a list of list? If this is not possible, any suggestion to move to a different data structure allowing that? thanks

推荐答案

在两个代码样本中定义矩阵的2种方式都有根本的不同.在第一行(第21行)中,将外部列表乘以3,实际上是将引用乘以内部列表.

There is a fundamental difference in the 2 ways you defined the matrix in both code samples. In the first (line 21) when you multiply the outer list by 3 you actually multiply the references to the inner list.

这是一个参数化的示例:

Here's a parameterized example:

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

如您所见,b的数字表示形式是您所期望的,但实际上它包含3个对a的引用.因此,如果您更改任何一个内部列表,它们都将更改,因为它们实际上是相同的列表.

As you can see the numerical representation of b is what you would expect, but it actually contains 3 references to a. So if you change either of the inner lists, they all change, because they are actually the same list.

代替乘法,您需要克隆执行以下操作的列表

Instead of multiplication you need to clone the lists doing something like this

new_list = old_list[:]

new_list = list(old_list)

对于嵌套列表,可以使用循环来完成.

In the case of nested lists, this can be done using loops.

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

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