python insert()函数解析

版权声明:本文版权归作者和CSDN共有,欢迎转载。转载时请注明原作者并保留此段声明,若不保留我也不咬你,随你了=-=。 https://blog.csdn.net/TeFuirnever/article/details/89282694

python insert()函数用于将指定对象插入列表的指定位置。

list.insert(index, 
	obj
)

参数:

  • index:对象obj需要插入的索引位置。

  • obj:要插入列表中的对象。

共有如下5种场景:

  • 1:index=0时,从头部插入obj。

  • 2:index > 0 且 index < len(list)时,在index的位置插入obj。

  • 3:当index < 0 且 abs(index) < len(list)时,从中间插入obj,如:-2 表示从倒数第1位插入obj。

  • 4:当index < 0 且 abs(index) >= len(list)时,从头部插入obj。

  • 5:当index >= len(list)时,从尾部插入obj。

list.insert(index = -1, obj)除外,当index = -1时,是插在倒数第二位的,也就是:

lst = [2,2,2,2,2,2]
lst.insert(-1,6)
print(lst)
> [2, 2, 2, 2, 2, 6, 2]

例子1:

lst = [2,2,2,2,2,2]
lst.insert(0,0)# index=0时,从头部插入obj
print(lst)
> [0, 2, 2, 2, 2, 2, 2]

例子2:

lst = [2,2,2,2,2,2]
lst.insert(6,7)# index > 0 且 index < len(list)时,在index的位置插入obj
print(lst)
> [2, 2, 2, 2, 2, 2, 7]

例子3:

lst = [2,2,2,2,2,2]
lst.insert(-2,6)# 当index < 0 且 abs(index) < len(list)时,从中间插入obj
print(lst)
> [2, 2, 2, 2, 6, 2, 2]

例子4:

lst = [2,2,2,2,2,2]
lst.insert(-20,10)# 当index < 0 且 abs(index) >= len(list)时,从头部插入obj
print(lst)
> [10, 2, 2, 2, 2, 2, 2]

例子5:

lst = [2,2,2,2,2,2]
lst.insert(30,20)# 当index >= len(list)时,从尾部插入obj
print(lst)
> [2, 2, 2, 2, 2, 2, 20]

猜你喜欢

转载自blog.csdn.net/TeFuirnever/article/details/89282694