gpt4 book ai didi

python - append 和 insert 都存在是有原因的吗?

转载 作者:太空狗 更新时间:2023-10-29 22:25:57 25 4
gpt4 key购买 nike

我肯定不是我想成为的 Python 大师,我主要在业余时间学习学习/实验,很可能我会为有经验的用户提出一个微不足道的问题......然而,我真的很想了解,这是一个对我有很大帮助的地方。

现在,在适当的前提之后,Python 文档说:

4.6.3. Mutable Sequence Types

s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])

[...]

s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])

此外:

5.1. More on Lists

list.append(x) Add an item to the end of the list. Equivalent to a[len(a):] = [x].

[...]

list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

所以现在我想知道为什么有两种方法可以做,基本上是同一件事?难道只有一个 append/insert(x, i=len(this)) 是可能的(而且更简单),其中 i 本来是一个可选参数并且,当不存在时,是否意味着添加到列表的末尾?

最佳答案

此处追加和插入的区别与正常用法和大多数文本编辑器中的区别相同。 Append 添加到列表的末尾,而 insert 添加在指定索引的前面。它们是不同方法的原因既是因为它们做不同的事情,也是因为 append 可以预期是一个快速操作,而 insert 可能需要一段时间,具体取决于大小列表的位置和插入位置,因为必须重新索引插入点之后的所有内容。

我不知道 insertappend 使用不同方法的真正原因,但我会做出有根据的猜测,这是为了帮助提醒开发人员固有的性能差异。而不是一个带有可选参数的 insert 方法,它通常以线性时间运行,除非未指定参数,在这种情况下它将以恒定时间运行(非常奇怪),第二种方法添加了 始终 恒定时间。这种类型的设计决策可以在 Python 的其他地方看到,例如当像 list.sort 这样的方法返回 None 而不是新列表时,作为 提醒它们是就地操作,而不是创建(和返回)新列表。

关于python - append 和 insert 都存在是有原因的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com