简体   繁体   English

如何将变量的值存储在列表而不是引用中?

[英]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 . 现在你只是将参考分配给ac ,这就是为什么当你修改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.

相关问题 如何将列表范围存储为变量? - How do I store the range of a list as a variable? 在Django中,如何使用列表项的String值获取对象变量的值? - In Django, how do I use a list item's String value to get an object's variable's value? 如何将变量(不是引用)的值附加到 Python 3.x 中的列表中? - How do I append the value of a variable (not the reference) into a list in Python 3.x? 我如何将循环打印值存储在变量或列表中 - How can i store for loop print value in variable or list 我如何从列表中删除一个项目并将其存储到 python 中的变量中 - How do i remove an item from a list and store it into a variable in python 如何将'count'变量的输出存储到列表中? (蟒蛇) - How do i store the output of the 'count' variable into a list? (python) 如何使用 Pandas 获取单元格的值并存储到变量中? - How do I get get the value of a cell & store into variable with Pandas? 如何将在 Tk 条目小部件上输入的值存储在变量中 - How do I store a value entered on a Tk entry widget in a variable django 中如何为变量添加默认值并存储在数据库中? - How do I add a default value to a variable and store in the database in django? 如何通过引用而不是按值复制列表的单个元素? - How do I copy a single element of a list by reference and not by value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM