(如果您想跳过凌晨 2 点的 Python 科学并切入正题,我的问题已在最后总结)
考虑以下几点:
1: animals = ['cat', 'cow', 'donkey', 'horse'] # we start with a list
2: animals_reference = animals # make another reference and assign it to animals
3: cat = animals[0] # refer cat to first element of animals
4: assert cat is animals[0] # no copy occurred, still same object
5: animals[0] = animals[0].capitalize() # change first element of list
6: assert cat is not animals[0] # animals[0] now refers to another object
7: assert animals_reference is animals # animals still points to the same object as before
我的理解是 Python 列表的底层结构是一个 C 数组(有很多动态的东西在进行,但归根结底,仍然是一个 C 数组。)
让我感到困惑的是:我们将 cat 设置为引用列表 (3) 的第一个元素。在 C 语言中,这是指它指向数组第一个元素的地址。
然后我们修改列表的第一个元素 (5)。
但是在这样做之后,cat 不再引用该对象 (6)。然而,列表引用也没有改变,因为在 (7) 中我们看到它从一开始就指向同一个对象。
这让我很困惑,因为它表明 cat 现在指的是其他东西,即使它从未被重新分配。
所以我进行了以下实验:
cat = animals[0] # refer cat to first element of animals
assert cat is animals[0] # no copy occurred, still same object
print("id of cat: {}".format(hex(id(cat))))
print("id of animals[0]: {}".format(hex(id(animals[0]))))
print("id of animals[]: {}".format(hex(id(animals))))
print("capitalizing animals[0]...")
animals[0] = animals[0].capitalize()
print("-id of cat: {}".format(hex(id(cat))))
print("-id of animals[0]: {}".format(hex(id(animals[0]))))
print("-id of animals[]: {}".format(hex(id(animals))))
输出:
id of cat: 0xffdda580
id of animals[0]: 0xffdda580
id of animals[]: 0xffddc828
capitalizing animals[0]...
-id of cat: 0xffdda580 # stayed the same!
-id of animals[0]: 0xffe12d40 # changed!!
-id of animals[]: 0xffddc828
这让我相信 Python 列表不一定是内存中的连续元素,对元素的更改只会指向内存中的其他位置?我的意思是,数组第一个元素的地址在内存中比数组本身的地址更早!
能够解释我所看到的内容的 lists use 的底层结构到底是什么?
请您参考如下方法:
这是一种思考方式:
1: animals = ['cat', 'cow', 'donkey', 'horse'] # we start with a list
2: animals_reference = animals # make another reference and assign it to animals
3: cat = animals[0] # refer cat to first element of animals
这不会使 cat 引用“动物的第一元素”,至少不是您所指的方式。它使 cat 引用动物的第一个元素所指的任何内容。在本例中,就是字符串“cat”。换句话说,表达式 animals[0] 本身就是对对象的引用。该对象是字符串 cat。当您执行 animals[0] 时,您将获得表达式 animals[0] 所指的对象。当您执行 cat = animals[0] 时,您将 cat 设置为引用该对象。
无法避免“取消引用”值 animals[0]。也就是说,没有办法说“给我 animals[0] 的指向性,这样当 animals[0] 开始指向其他东西时,我的新变量将还指着别的东西”。您只能获取 animals[0] 所指的内容,而不能获取其所指本身。
因此:
4: assert cat is animals[0] # no copy occurred, still same object
5: animals[0] = animals[0].capitalize() # change first element of list
在这里,您可以更改 animals[0] 指向的位置。但是您将 cat 设置为 animals[0] 过去指向的地方。所以现在 cat 和 animals[0] 指向不同的东西。字符串 "cat" 没有改变(这就是为什么你的 is 测试仍然显示值是相同的);只是 animals[0] 不再指向该字符串,而是开始指向字符串 "Cat"。
