我有这样的代码:
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”,它也会在第一个可用索引处插入。那么“插入”是如何做出决定的呢?
最佳答案
来自Python3 doc :
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).
没有提到的是,您可以给出超出范围的索引,然后 Python 将追加到列表中。
如果您深入研究 Python implementation您可以在执行插入操作的 ins1
函数中找到以下内容:
if (where > n)
where = n;
所以基本上 Python 会将你的索引最大化到列表的长度。
关于python - python 中的 list.insert() 实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614538/