What does list.insert() in actually do in python?(list.insert() in 实际上在 python 中做了什么?)
问题描述
我有这样的代码:
squares = []
for value in range(1, 5):
squares.insert(value+1,value**2)
print(squares)
print(squares[0])
print(len(squares))
输出是:
[1, 4, 9, 16]
1
4
因此,即使我要求 python 在索引2"处插入1",它也会在第一个可用索引处插入.那么插入"是如何做出决定的呢?
So even if I ask python to insert '1' at index '2', it inserts at the first available index. So how does 'insert' makes the decision?
推荐答案
来自 Python3文档:
list.insert(i, x)
在给定位置插入一个项目.首先参数是要插入的元素的索引,所以a.insert(0, x) 在列表的前面插入,而 a.insert(len(a),x) 等价于 a.append(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).
没有提到的是你可以给出一个超出范围的索引,然后 Python 会追加到列表中.
What is not mentionned is that you can give an index that is out of range and Python will then append to the list.
如果您深入研究 Python 实现,您会发现执行插入的 ins1
函数中的以下内容:
If you dig into the Python implementation you find the following in the ins1
function that does the insertion:
if (where > n)
where = n;
所以基本上 Python 会将您的索引最大化到列表的长度.
So basically Python will max out your index to the length of the list.
这篇关于list.insert() in 实际上在 python 中做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:list.insert() in 实际上在 python 中做了什么?


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01