[英]How to assign an element from a 2D array to a new variable without changing its original value in python?
I want to take a value from a 2D array (so this value has a type of array) and assign it to a new variable.我想从 2D 数组中获取一个值(因此该值具有数组类型)并将其分配给一个新变量。 But when I make changes to this new variable, its original value in that 2D array also changes.
但是当我对这个新变量进行更改时,它在该二维数组中的原始值也会发生变化。 I want to know if there is a correct way that I can do this?
我想知道是否有正确的方法可以做到这一点?
Here is my example code.这是我的示例代码。
a = [[1],[2],[3]]
b = a[1]
b.append(2)
a.append(b)
print(a)
print(b)
In the output, a, b will be在 output 中,a、b 将是
a = [[1], [2, 2], [3], [2, 2]]
b = [2, 2]
Where I don't want a[1] to be changed as well.我不希望 a[1] 也被更改。 If someone can help me figure this out?
如果有人可以帮我解决这个问题? Thanks.
谢谢。
This is probably one of the most confusing concept for beginner, when you are doing subscription slicing, b = a[1]
, the reference to first array a
has been passed to b
, which you whatever action you do to b
, will be done to a[1]
.对于初学者来说,这可能是最令人困惑的概念之一,当您进行订阅切片时,
b = a[1]
,对第一个数组a
的引用已传递给b
,您对b
执行的任何操作都将完成到a[1]
。 unless you make a complete copy of the original array, any action to subscripted will lead to change in original , therefore, whenever you want to work with array without changing its initial value, copy it manually.除非您制作原始数组的完整副本,否则对下标的任何操作都会导致 original 发生变化,因此,无论何时您想在不更改其初始值的情况下使用数组,请手动复制它。
a = [[1],[2],[3]]
# in your case it is nested so it will be a bit intricate
ac = list(map(lambda x:list(map(lambda y:y, x)), a))
b = ac[1]
b.append(2)
a.append(b)
print(a)
print(b)
# [[1], [2], [3], [2, 2]]
# [2, 2]
Because a[1]
is an array, passing it to b
will pass it by reference and not by value .因为
a[1]
是一个数组,将它传递给b
将通过引用而不是通过值传递它。 You can use您可以使用
b = a[1].copy()
to make a new instance of a[1]
without effecting the original a[1]
.在不影响原始
a[1]
的情况下a[1]
的新实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.