简体   繁体   English

在列表列表中编辑项目时遇到麻烦

[英]Trouble with editing items in list of lists

I wanted to a make a list of list using pythons and I know two methods to do it. 我想使用python列出列表,我知道有两种方法可以做到这一点。

The first method is like so: 第一种方法是这样的:

l = []
l_in = []
for j in range(2):
   l_in.append("1")
print l_in
for i in range(2):
   l.append(l_in)
print l

and the second method is: 第二种方法是:

l = []
for i in range(2):
   l.append([1]*2)
print l

Both these methods creates a list 这两种方法都会创建一个列表

l = [['1', '1'], ['1', '1']] 

I want to change only on element int this list say the (1,1) element. 我只想更改此列表中的元素int (1,1)元素。 If I do 如果我做

l[1][1] = "Something I want to replace with"

the element should be replaced. 该元素应被替换。 This works fine for the second method. 这对于第二种方法很好用。 But if I use the first method both (1,1) and (0,1) changes to "Something I want to replace with" . 但是,如果我使用第一种方法,则(1,1)(0,1)将变为"Something I want to replace with"为的"Something I want to replace with"

Can someone tell me why using the first method gives this output? 有人可以告诉我为什么使用第一种方法给出此输出吗?

It's because in the first method, in the second loop you are appending the same list twice. 这是因为在第一种方法中,在第二个循环中,您将两次附加相同的列表。

for i in range(2):
    l.append(l_in)

Now whenever you're modifying an element in l , you are actually modifying elements in one list. 现在,每当您修改l的元素时,实际上就是在修改一个列表中的元素。 An easy way to understand is to look at the values the builtin id() gives for the content of l . 一种简单的理解方法是查看内置id()l的内容提供的值。

>>> map(id, l)
[32750120, 32750120]

You can see that both elements in l share the same id (and the same memory address). 您可以看到l中的两个元素共享相同的ID(和相同的内存地址)。 They both refer to the same list l_in . 它们都引用相同的列表l_in

As Aशwini चhaudhary suggested, an easy fix is l.append(l_in[:]) where the [:] creates a copy of the list l_in . 如Aशwiniचhaudhary所建议的那样,一个简单的解决方法是l.append(l_in[:]) ,其中[:]创建列表l_in的副本。

l = []
l_in = []
for j in range(2):
   l_in.append("1")
print l_in
for i in range(2):
   l.append(l_in[:])
print l

You can also create lists of lists with list and generator comprehensions. 您还可以使用列表和生成器理解来创建列表列表。 Some examples below: 以下是一些示例:

# empty lists..
>>> [[] for _ in range(4)]
[[], [], [], []]

# generator expression..
>>> list([] for _ in range(4))
[[], [], [], []]

# [1, 1] for each sublist.
>>> list([1, 1] for _ in range(4))
[[1, 1], [1, 1], [1, 1], [1, 1]]

Here's the help() on id() : 这是id()上的help() id()

Help on built-in function id in module __builtin__:

id(...)
    id(object) -> integer

    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory address.)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM