提问人:Aguy 提问时间:2/18/2020 更新时间:2/18/2020 访问量:31
为什么从分配给另一个列表的列表中获取一个切片不会更改原始列表?
Why is taking a slice of a list which is assigned to another list not changing the original?
问:
我有一个类是数学张量的表示。类中的张量存储为单个列表,而不是另一个列表中的列表。这意味着将存储为 .[[1, 2, 3], [4, 5, 6]]
[1, 2, 3, 4, 5, 6]
我制作了一个函数和一个函数来处理在单列表格式下获取此张量的切片。例如,将成为上述列表。但是,当我为这个切片分配一个新值时,原始张量不会更新。__setitem__()
slice(1, None, None)
slice(3, None, None)
以下是简化代码的样子
class Tensor:
def __init__(self, tensor):
self.tensor = tensor # Here I would flatten it, but for now imagine it's already flattened.
def __setitem__(self, slices, value):
slices = [slices]
temp_tensor = self.tensor # any changes to temp_tensor should also change self.tensor.
for s in slices: # Here I would call self.slices_to_index(), but this is to keep the code simple.
temp_tensor = temp_tensor[slice]
temp_tensor = value # In my mind, this should have also changed self.tensor, but it hasn't.
也许我只是愚蠢,不明白为什么这不起作用。也许我的实际问题不仅仅是“为什么这不起作用?”,而是“有没有更好的方法可以做到这一点?”。感谢您给我的任何帮助。
笔记:
列表的每个“维度”必须具有相同的形状,因此不允许使用。[[1, 2, 3], [4, 5]]
这段代码被大大简化了,因为还有许多其他帮助程序函数和类似的东西。
在我会扁平化列表,但正如我刚才所说,为了简单起见,我把它和.__init__()
self.slice_to_index()
答:
1赞
Netwave
2/18/2020
#1
您不应将 python 变量视为 in 或 。把它们看作是你贴在价值观上的标签。请看这个例子:c++
java
>>> l = []
>>> l.append
<built-in method append of list object at 0x7fbb0d40cf88>
>>> l.append(10)
>>> l
[10]
>>> ll = l
>>> ll.append(10)
>>> l
[10, 10]
>>> ll
[10, 10]
>>> ll = ["foo"]
>>> l
[10, 10]
正如你所看到的,变量首先指向同一个列表,但后来我们只是让它指向另一个列表。修改后者不会修改 指向的原始列表。ll
l
ll
l
因此,就您而言,如果您想指向一个新值,只需执行以下操作:self.tensor
class Tensor:
def __init__(self, tensor):
self.tensor = tensor # Here I would flatten it, but for now imagine it's already flattened.
def __setitem__(self, slices, value):
slices = [slices]
temp_tensor = self.tensor # any changes to the list pointed by temp_tensor will be reflected in self.tensor since it is the same list
for s in slices:
temp_tensor = temp_tensor[slice]
self.tensor = value
评论
0赞
Aguy
2/18/2020
这是有道理的,所以我现在可以看到为什么我原来的功能不起作用了。我会试试你的方法。
上一个:使可变元素的排序列表保持最新
评论