简体   繁体   English

在python中将元素从一个列表复制到另一个

[英]Copying element from one list to another in python

Let's say that I created two different lists: 假设我创建了两个不同的列表:

listA = [0, 0, 0]
listB = [1, 1, 1]

I want to make the an element in listB refer to the same object as an element in listA. 我想使listB中的一个元素引用与listA中的元素相同的对象。 So that the element in both lists change together. 这样两个列表中的元素都会一起更改。

listB[2] = listA[0]
>>listB[2]
>>0

listB[2] = 2
>>listA[0]
>>2

However doing the above just passes the value of the elements, so the lists are still referring to individual objects. 但是,执行上述操作只是传递元素的值,因此列表仍然引用单个对象。 Is there a method or a different data structure that could give me the desired effect? 有没有一种方法或其他数据结构可以使我达到预期的效果?

Here's a simple idea to get you started, and also help you understand better what's going on: 这是一个入门的简单想法,还可以帮助您更好地了解正在发生的事情:

>>> listA = [[0], [0], [0]]
>>> listB = [[1], [1], [1]]
>>> listA[0] = listB[0]
>>> listA
[[1], [0], [0]]
>>> listB[0][0] = 2
>>> listB
[[2], [1], [1]]
>>> listA
[[2], [0], [0]]

But be careful: 不过要小心:

>>> listB[0] = [3]
>>> listB
[[3], [1], [1]]
>>> listA
[[2], [0], [0]]

You could write a class that makes this invisible so it looks more like a list and is easier to use without making mistakes. 您可以编写一个使它不可见的类,使它看起来更像一个列表,并且易于使用而不会出错。

You can't do that. 你不能那样做。 You can either make listA and listB themselves be the same object, in which case all their indices will reflect any changes made to either, or you can make them separate objects, in which case none of their indices will reflect changes. 您可以让listAlistB自己是同一个对象,在这种情况下, 所有的指数将反映任何所作的任何修改,或者你可以让他们独立的物体,在其指数的情况下, 没有人会反映更改。 You can't make two lists that are "joined at the hip", sharing only some of their index references. 您不能创建两个仅“共享”的列表,而仅共享它们的某些索引引用。

Suppose that the value of listB[2] is some object called obj . 假设listB[2]的值是一个称为obj When you do something like listB[2] = 2 , you aren't changing obj ; 当您执行诸如listB[2] = 2 ,您不会更改obj you are changing listB (by making its index 2 point to some other object). 您正在更改listB (通过使其索引2指向其他某个对象)。 So you can't make listA[2] "reflect" listB[2] unless listA and listB are the same object. 因此,除非listAlistB是同一对象,否则不能使listA[2] “反射” listB[2] You can certainly make listA[2] and listB[2] refer to the same object, but that won't affect what happens when you do listB[2] = 2 , because that operation won't affect that shared object at all. 您当然可以使listA[2]listB[2]指向同一个对象,但这不会影响listB[2] = 2时发生的情况,因为该操作根本不会影响该共享对象。

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

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