内存 - Python list内容的改变问题
怪我咯
怪我咯 2017-04-17 15:46:44
0
3
262

Pyhton 新手。
今天看教程的时候实验了如下代码:

old = 'abc'
old.replace('a','A')
print old

这里old 并没有被替换,这个我可以理解,因为replace方法返回了一个新的对象,old仍指向原对象。
所以打印的仍然是abc

替换成:

old = 'abc'
new = old.replace('a','A')
print new

即可。
结果就是Abc了。

但是,又想到了这个问题,代码如下:

stu1 = 'Tom'
stu2 = 'John'

classMates = [stu1,stu2]

print classMates

stu2 = 'Marry'

print classMates

结果却是:
['Tom','John']
['Tom','John']

而不是预期的:
['Tom','John']
['Tom','Marry']

如果再对list赋值一次:

classMates = [stu1,stu2]

就可以得到想要的效果。

所以想问的是list创建的时候指向的是stu1和stu2的位置么,为什么stu2中的内容变了list中的不会变呢?
还是像最开始的那个例子一样,产生了一个新的list?现在的classMates没有指向更改后的list而是还是指向原来的list?

谢谢!

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
巴扎黑

You need to know what the assignment operation in Python means:

The simplest assignment, such as a = b, is to associate the object referred to by b with the name a, so you can use The name a is used to refer to this object. a = b,是将 b 所指称的对象与名字 a 关联起来,这样你就可以用名字 a 来指称这个对象了。

所以,你的代码的意思是:

stu1 = 'Tom'             # 我把 'Tom' 这个字符串叫作 stu1
stu2 = 'John'            # 我把 'John' 这个字符串叫作 stu2

classMates = [stu1,stu2] # 我把列表叫作 classMates。在这里,名字的意义被表达,所以 classMates 是 ['Tom', 'John']

print classMates

stu2 = 'Marry'           # 我把 'Marry' 这个字符串叫作 stu2。之前这个名字属于另一个对象,但从此刻起它属于 'Marry' 了

print classMates         # classMates 就是 ['Tom', 'John'] 啊

stu2

So, your code means:

rrreee

stu2 has no content, it's just the name. A name can refer to an object.

Understand not memorize! Python is not C! Not even C++! 🎜 🎜Forgot to post a related reply. 🎜
伊谢尔伦
stu1 = 'Tom'
stu2 = 'John'

These two sentences create two string objects: 'Tom' and 'John' and assign the references of these two objects to stu1 and stu2.

classMates = [stu1,stu2]

The two string objects become elements of the list, and the reference counts are +1 respectively, which is 2

stu2 = 'Marry'

'John' reference count -1 'Marry' reference count +1

小葫芦
list     = [1,2,3]
list2    =  list
list2[0] = 100
print list

a = 1
b = a
b = 2
print a

Remember the difference between lists and variables. list is quoted. Both list and list2 point to the same address
The variables are not referenced.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!