新列表中的值更改会影响列表中以前的列表值 [英] Value changes in new list impact previous list values, within a list of lists

查看:97
本文介绍了新列表中的值更改会影响列表中以前的列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找随机生成一个列表,并更改列表中的一个元素以创建新列表.同时跟踪所有生成的列表.

I am looking to randomly generate a list and change one element in the list to create a new list. Whilst keeping track of all the generated lists.

例如:

values_possible = [0,0.5,1]
combinations = []
combinations.append([random.choice(values_possible) for i in range(8)])

让我们说这会产生

[0,0.5,0.5,0,0.5,0.5,1.0,1.0]    

然后,如果我复制此列表并更改一个元素,例如,组合[1] [1]

then if I copy this list and change one element, say combinations[1][1]

# set a new list to equal the first and then change one element
combinations.append(combinations[0])
combinations[1][1] = 0.33

print(combinations[0])
print(combinations[1])

这将返回

[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]

似乎组合[0] [1]和组合[1] [1]均已更改为0.33.有办法解决吗?请问为什么会这样以及我对清单有什么误解?我曾期待以下输出:

it seems both combinations[0][1] and combinations[1][1] have changed to 0.33. Is there a way to solve this? May I ask why this happens and what I am misunderstanding about lists? I had expected the following output:

[0,0.5,0.5,0,0.5,0.5,1.0,1.0]
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]

推荐答案

您的问题的简短答案是使用冒号:

The short answer to your question is using colon:

 combinations.append(combinations[0][:])

为什么?原因是在python中,当您将变量追加到列表中时,变量会通过其引用追加.在您的示例中,这意味着列表中的两个元素相同.它们指向内存中的相同地址,如果您修改它们中的任何一个,则两个值都将更改为一个,并使用相同的内存块.

Why? The reason is that in python when you append a variable into your list, the variable is appended by its reference. In your example, it means that the two elements in the list are the same. They are pointing to the same address in the memory and if you modify either of them, both value will change as they are one and using the same chunk of memory.

如果您要复制变量的值(在您的情况下是组合[0]),则需要使用冒号来复制值并将其放入内存的另一部分(它将占用另一个具有不同地址的内存块),在这种情况下,您可以分别对其进行修改.

If you want to copy the values of a variable, in your case, combinations[0], you need to use colons to make a copy of values and put them in another part of memory (it will occupy another chunk of memory with different address) In this case, you can modify them separately.

您还可以查看以下问题和答案: python list by值不通过引用

You can also take a look at this question and answer: python list by value not by reference

我希望这会有所帮助.

这篇关于新列表中的值更改会影响列表中以前的列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆