Python编程:列表 [英] Python programming: lists

查看:79
本文介绍了Python编程:列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gene = [0,5,1,0,7,1]

originalGene = gene



gene [0] = 2

打印originalGene



输出:[2,5,1,0,7,1]

问题:为什么'originalGene'列表的内容也会改变?



我尝试过:



我试图多次运行代码,我尝试使用变量进行操作,但它与变量一起工作,但没有列表......

gene = [0, 5, 1, 0, 7, 1]
originalGene = gene

gene[0] = 2
print originalGene

OUTPUT: [2, 5, 1, 0, 7, 1]
QUESTION: Why do the contents of the 'originalGene' list get changed as well ?

What I have tried:

I have tried to run the code multiple times and I have tried doing it with variables and it WORKS with variables but not with lists...

推荐答案

可能是因为 originalGene gene 都是真实列表的指针,所以当 gene [0] = 2 更改列表的第一个元素,它似乎同时更改两个变量。

你需要学习python更多细节。
It is probably because originalGene and gene are both pointers to the real list, so when gene[0] = 2 change the first element of the list, it appear to change both variables at same time.
You need to study python for more details.


你应该复制一份:

You should take a copy:
gene = [0, 5, 1, 0, 7, 1] 
originalGene = gene[:]


gene = [0,5,1,0,7,1]

originalGene = gene



这就是原因。两者都指向同一个列表。查看这两个列表的ID。它应该是相同的。
gene = [0, 5, 1, 0, 7, 1]
originalGene = gene

This is the reason. Both points to the same list. Check out id of both these list. It should be same.


这篇关于Python编程:列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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