关于linux:python-列表中插入数据

4次阅读

共计 754 个字符,预计需要花费 2 分钟才能阅读完成。

insert() 往列表的指定地位增加元素,举个例子:

insert 的列子

1 a = [“hello”, “world”, “dlrb”]
2 a.insert(1, “girl”)
3 print(a)
输入后果:

[‘hello’, ‘girl’, ‘world’, ‘dlrb’]
咱们在列表 a 的地位 1 插入元素 girl

A = [1,2,3,4,5,6,8]
A.insert(6, 7)
print(A)

result:
[1,2,3,4,5,6,7,8]

insert 共有如下 5 种场景:

  • 1:index= 0 时,从头部插入 obj。
  • 2:index > 0 且 index < len(list) 时,在 index 的地位插入 obj。
  • 3:当 index < 0 且 abs(index) < len(list) 时,从两头插入 obj,如:-1 示意从倒数第 1 位插入 obj。
  • 4:当 index < 0 且 abs(index) >= len(list) 时,从头部插入 obj。
  • 5:当 index >= len(list) 时,从尾部插入 obj。

append 与 insert 的区别

两者都是对 python 内的列表进行操作,append() 办法是值在列表的开端减少一个数据项,insert() 办法是指在某个特定地位前加一个数据项。

Python 内的 list 实现是通过数组实现的,而不是链表的模式,所以每当执行 insert() 操作时,都要将插入地位的元素向后挪动能力在相应的地位插入元素,执行 append() 操作时,如果调配的空间还足够大的话那么就能够间接插到最初,如果空间不够的话就须要将已有的数据复制到一片更大的空间后再插入新元素,insert() 空间不够的话也是同样。

参考:
python list insert
append list in python
python 3 list methods examples
sort list in python

正文完
 0