[英]How do I store a variable's value in a list instead of a reference?
a = ['a']
b = ['b']
c = a
ab = [a,b]
print(c)
print(ab)
a[0] = 'c'
print(c)
print(ab)
Returns: 返回:
['a']
[['a'], ['b']]
['c']
[['c'], ['b']]
I wanted the c list to remain what it was ie ['a']. 我希望c列表保持原样即['a']。 But it changed after I changed the element in the a list. 但是在我更改了列表中的元素后,它发生了变化。 Why does this happen and how, if at all, can I avoid it. 为什么会发生这种情况,如果有的话,我可以避免它。
You need to copy the list a
and assign it to c
. 您需要复制列表a
并将其分配给c
。 Right now you are just assigning the reference to a
to c
, which is why when you modify a
you also modify c
. 现在你只是将参考分配给a
到c
,这就是为什么当你修改a
你也修改c
。 There are multiple ways to copy a
, I think the easiest to read uses the list constructor: 有多种方法可以复制a
,我觉得最容易阅读使用列表构造函数:
c = list(a)
Alek's or mtitan8's solutions are probably the most convenient. Alek或mtitan8的解决方案可能是最方便的。 To be very explicit, you can import copy
and then use c = copy.copy(a)
要非常明确,您可以import copy
然后使用c = copy.copy(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.