考虑到以下两个例子,我对python如何处理列表中的元素有点困惑:
第一个例子:
import random a = [[1,2],[3,4],[5,6],[7,8]] b = [0.1,0.2] c = random.choice(a) c[:] = b print(a)第二个例子:
import random a = [1, 2, 3, 4, 5, 6, 7, 8] b = 0.1 c = random.choice(a) c = b print(a)在第一个例子中,列表a中的内容被改变; 而在第二个例子中,列表a的内容没有改变。 这是为什么?
I am a little confused about how python deal with reference to an element in a list, considering these two examples:
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; while in the second example, the content of list a is not changed. Why is that?
最满意答案
让我们从第二种情况开始。 你写
c = random.choice(a)所以名称c绑定到a的某个元素,然后
c = b所以名称c绑定到某个其他对象(名称b所指的对象 - 浮点数0.1)。
现在到第一个案例。 你开始吧
c = random.choice(a)所以名称c绑定到a中的一个对象,这本身就是一个列表。 然后你写
c[:] = b这意味着,通过其他列表替换名称c绑定的列表中的所有项目。 实际上,这称为切片赋值 ,并且基本上是用于调用c绑定到的对象的方法的语法糖。
然后,区别在于,在第一种情况下,它不仅将名称首先绑定到一个对象,然后绑定到另一个对象。 它将名称绑定到列表,然后使用此名称间接调用列表的方法。
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 = bso the name c gets bound to some other object (the one to which the name b is referring - the float 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. Then you write
c[:] = bwhich means, replace all items in the list bound to by the name c, by some other list. In fact, this is called slice assignment, and is basically syntactic sugar for calling a method of the object to which c is bound.
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.
更多推荐
发布评论