最高效的方法
您也可以使用 slice 索引 在列表中插入元素。例如:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index at which you want to insert item
>>> b = a[:] # Created copy of list "a" as "b".
# Skip this step if you are ok with modifying the original list
>>> b[insert_at:insert_at] = [3] # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
对于在给定索引处同时插入多个元素,您只需使用要插入的多个元素的list。例如:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index starting from which multiple elements will be inserted
# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]
>>> a[insert_at:insert_at] = insert_elements
>>> a # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]
了解更多切片索引,可以参考:Understanding slice notation。
注意:在 Python 3.x 中,slice indexing 和 list.index(...) 之间的性能差异显着减小,两者几乎相等.但是,在 Python 2.x 中,这种差异非常明显。我在这个答案后面分享了性能比较。
使用列表理解的替代方案 (但在性能方面非常慢):
作为替代方案,也可以使用 list comprehension 和 enumerate 来实现。 (但请不要这样做。这只是为了说明):
>>> a = [1, 2, 4]
>>> insert_at = 2
>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]
所有解决方案的性能比较
这是timeit 将所有答案与 Python 3.9.1 和 Python 2.7.16 上的 1000 个元素列表的比较。答案按两个 Python 版本的性能顺序列出。
Python 3.9.1
-
My answer 使用切片插入 - 最快(每个循环 2.25 微秒)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
-
Rushy Panchal's answer 使用list.insert(...) 获得最多票数 - 第二(每个循环 2.33 微秒)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 5: 2.33 µsec per loop
-
ATOzTOA's accepted answer 基于切片列表的合并 - 第三个(每个循环 5.01 微秒)
python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
50000 loops, best of 5: 5.01 µsec per loop
-
My answer 与 List Comprehension 和 enumerate - 第四 (非常慢,每个循环 135 微秒)
python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
2000 loops, best of 5: 135 µsec per loop
Python 2.7.16
-
My answer 使用切片插入 - 最快(每个循环 2.09 微秒)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 3: 2.09 µsec per loop
-
Rushy Panchal's answer 使用list.insert(...) 获得最多票数-第二(每个循环2.36 µsec)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 3: 2.36 µsec per loop
-
ATOzTOA's accepted answer 基于切片列表的合并 - 第三个(每个循环 4.44 微秒)
python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
100000 loops, best of 3: 4.44 µsec per loop
-
My answer 与 List Comprehension 和 enumerate - 第四(非常慢,每个循环 103 微秒)
python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
10000 loops, best of 3: 103 µsec per loop