[英]Python - Append list to list
I am trying to solve a problem about lists.我正在尝试解决有关列表的问题。 For output I want to add all the lists to one final list (
ans
).对于输出,我想将所有列表添加到一个最终列表 (
ans
)。
But when I append the second list, the first list becomes equal to the second one.但是当我附加第二个列表时,第一个列表变得等于第二个列表。 I can't understand why this happens.
我不明白为什么会发生这种情况。
ls = list()
ans = []
n = int(input())
for _ in range(n):
cmd = input()
if cmd == "insert":
i, e = map(int, input().split())
ls.insert(i, e)
elif cmd == "print":
ans.append(ls)
elif cmd == "remove":
e = int(input())
ls.remove(e)
elif cmd =="append":
e = int(input())
ls.append(e)
elif cmd == "sort":
ls.sort()
elif cmd == "pop":
ls.pop()
elif cmd == "reverse":
ls.reverse()
else:
print("invalid input")
print(ans)
Input:输入:
12
insert
0 5
insert
1 10
insert
0 6
print
remove
6
append
9
append
1
sort
print
pop
reverse
print
When you append a list into a list, ie ans.append(ls)
you actually pass it by reference.当您将列表附加到列表中时,即
ans.append(ls)
您实际上是通过引用传递它。 So when you append ls
3 times into ans
it will append the same reference of ls
.因此,当您将
ls
附加 3 次到ans
,它将附加ls
的相同引用。
If you don't want to append by reference, you should give a copy of the list.如果您不想通过引用附加,则应提供列表的副本。 And in a more complicated list you probably should do deep copy.
在更复杂的列表中,您可能应该进行深复制。
Here is to append a copy:这是附加一个副本:
ans.append(ls.copy())
Hope it helps!希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.