最高效的方法
您也可以使用列表中的切片索引插入元素。例如:
>>> 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]
使用列表理解的替代方法 (但性能很慢):
作为替代方案,它可以使用来实现清单理解与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.4.5的1000个元素列表的比较:
使用切片插入的地雷解答 -最快(每个循环3.08微秒)
mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 3: 3.08 µsec per loop
ATOzTOA接受的基于切片列表合并的答案 -秒(每个循环6.71微秒)
mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
100000 loops, best of 3: 6.71 µsec per loop
鲁希·潘查尔(Rushy Panchal)的票数最多,答案是list.insert(...)
-第三(每个循环26.5 微秒)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
10000 loops, best of 3: 26.5 µsec per loop
我的回答与列表理解和enumerate
四- (每圈168微秒很慢)
mquadri$ 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, )) ]"
10000 loops, best of 3: 168 µsec per loop
b = a[:].insert(2,3)
似乎很短,不会影响原始列表,并且具有描述性。