简体   繁体   English

在 python 的列表中附加列表中的项目时出现问题

[英]Issue while appending item in list in a list in python

I think similar questions exist but I can't seem to find them out我认为存在类似的问题,但我似乎无法找到它们

x=list(([],)*3)
x[0].append(1)
x[1].append(2)
x[2].append(3)
print(x)

I want the result to look like this:我希望结果如下所示:

[[1],[2],[3]]

But instead, I get:但相反,我得到:

[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Also I really don't want to use any loops but if it is necessary then I'll try另外我真的不想使用任何循环,但如果有必要,我会尝试

Just realized you don't want to use a for loop.刚刚意识到您不想使用 for 循环。

Option 1: no for loops:选项 1:没有 for 循环:

x = []
x.append([1])
x.append([2])
x.append([3])
print(x)
> [[1], [2], [3]]

Option 2: using loops.选项 2:使用循环。

Easiest and cleanest way is to use list comprehension like this:最简单和最干净的方法是使用这样的列表理解

x = [[i] for i in range(1,4)]
print(x)
> [[1], [2], [3]]

Or you can use a plain for loop and create an empty list before:或者您可以使用普通的 for 循环并在之前创建一个空列表:

result = []
for i in range(1,4):
    result.append([i])
result

Instead of the first line, use而不是第一行,使用

x = [[] for _ in range(3)]

In the current code, x is a list of the empty lists which are actually the same object .在当前代码中, x是空列表的列表,它们实际上是相同的 object That's how [...] * n works;这就是[...] * n的工作原理; it repeats the same objects n times.它重复相同的对象n次。 So appending an item to one of these empty lists would append the item to the others, because they are the same.因此,将一个项目附加到这些空列表之一会将 append 项目附加到其他项目,因为它们是相同的。

You can create an empty list first and starts appending each element as a list.您可以先创建一个空列表,然后开始将每个元素附加为列表。

x=[]
x.append([1])
x.append([2])
x.append([3])
print(x)

All the lists are copies (or views would be more accurate) of each other.所有列表都是彼此的副本(或者视图会更准确)。 Any changes made to one list will make changes to all the list.对一个列表所做的任何更改都会对所有列表进行更改。 You'll have to manually create lists or use list comprehension to make separate lists.您必须手动创建列表或使用列表推导来制作单独的列表。 @j1-lee has already told you about list comprehension so I won't copy that. @j1-lee 已经告诉过你列表理解,所以我不会复制它。 Create manual lists and try to append the data.创建手动列表并尝试 append 数据。 Your code:你的代码:

x=[[],[],[]]
x[0].append(1)
x[1].append(2)
x[2].append(3)
print(x)

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

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