引用列表中的元素(Reference to an element in a list)

编程入门 行业动态 更新时间:2024-10-18 12:34:12
引用列表中的元素(Reference to an element in a list)

考虑到以下两个例子,我对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 = b

so 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[:] = b

which 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.

更多推荐

本文发布于:2023-08-04 09:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415262.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   列表中   Reference   element   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!