简体   繁体   English

引用列表中的元素

[英]Reference to an element in a list

I am a little confused about how python deal with reference to an element in a list, considering these two examples: 考虑到以下两个示例,我对python如何处理对列表中元素的引用感到有些困惑:

First example: 第一个例子:

import random
a = [[1,2],[3,4],[5,6],[7,8]]
b = [0.1,0.2]
c = random.choice(a)
c[:] = b
print(a)

Second example: 第二个例子:

import random
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = 0.1
c = random.choice(a)
c = b
print(a)

In first example, the content in list a is changed; 在第一个示例中,列表a中的内容已更改; while in the second example, the content of list a is not changed. 而在第二个示例中,列表a的内容未更改。 Why is that? 这是为什么?

Let's start with the second case. 让我们从第二种情况开始。 You write 你写

c = random.choice(a)

so the name c gets bound to some element of a, then 所以名称c被绑定到a的某个元素上,然后

c = b

so the name c gets bound to some other object (the one to which the name b is referring - the float 0.1). 因此名称c被绑定到其他对象(名称b所指的对象-浮点数0.1)。


Now to the first case. 现在到第一种情况。 You start with 你开始

c = random.choice(a)

So the name c gets bound to an object in a , which is a list itself. 因此,名称c被绑定到列表中的对象a Then you write 然后你写

c[:] = b

which means, replace all items in the list bound to by the name c , by some other list. 这意味着将名称c绑定的列表中的所有项目替换为其他列表。 In fact, this is called slice assignment , and is basically syntactic sugar for calling a method of the object to which c is bound. 实际上,这称为切片分配 ,基本上是用于调用c绑定到的对象的方法的语法糖。


The difference, then, is that in the first case, it doesn't just bind a name first to one object, then to another. 区别在于,在第一种情况下,它不只是将名称先绑定到一个对象,然后再绑定到另一个。 It binds a name to a list, then uses this name to indirectly call a method of the list. 它将名称绑定到列表,然后使用该名称间接调用列表的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM