Python的insert()方法与通过切片插入之间的实现和性能差异 [英] Implementation and performance difference between Python's insert() method and inserting by slicing

查看:94
本文介绍了Python的insert()方法与通过切片插入之间的实现和性能差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过以下方式在python列表中插入元素之间有什么区别?

What is the difference between inserting an element in a python list in the following ways?

myList.insert(at, myValue)
myList[at:at] = [myValue]

我已经进行了一些测试,并且两者的性能非常相似,但是切片插入始终会产生更好的结果.我的问题是关于实现和性能的差异,而不是行为.

I have run some tests and the performance of the two are very similar, but the slicing insert consistently produces slightly better results. My question is regarding the difference in implementation and performance, not the behaviour.

推荐答案

我们具有相同的行为,请参见下面的内容:

We have the same behaviour, see bellow:

默认行为是在给定索引处插入项目; 每个大索引处的值都移到最后一个位置.

The default behaviour is to insert the item at the given index; each value at greater index are shifted one position to the end.

>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list.insert(5, 'item')
>>> my_list
['a', 'b', 'c', 'd', 'e', 'item', 'f', 'g']

>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list.insert(-3, 'item')
>>> my_list
['a', 'b', 'c', 'd', 'item', 'e', 'f', 'g']

如果列表为空,则该项目将正常添加.

If the list is empty, the item is appended normally.

>>> my_list = []
>>> my_list.insert(5, 'item')
>>> my_list
['item']

>>> my_list = []
>>> my_list.insert(-3, 'item')
>>> my_list
['item']

如果索引超出范围,则如果索引为正,则该项将追加到末尾;如果索引为负,则将其追加到末尾. 没有异常.

If the index is out of bounds, the item is appended to the end if the index is positive or to the beginning if negative. No exception is raised.

>>> my_list = ['a', 'b']
>>> my_list.insert(5, 'item')
>>> my_list
['a', 'b', 'item']

>>> my_list = ['a', 'b']
>>> my_list.insert(-3, 'item')
>>> my_list
['item', 'a', 'b']

我们在切片符号上具有完全相同的行为, 如果索引范围相同:

We have exactly the same behaviour with slice notation, in the case of a range of same indexes:

>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list[5:5] = ['item']
>>> my_list
['a', 'b', 'c', 'd', 'e', 'item', 'f', 'g']

>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list[-3:-3] = ['item']
>>> my_list
['a', 'b', 'c', 'd', 'item', 'e', 'f', 'g']

>>> my_list = []
>>> my_list[5:5] = ['item']
>>> my_list
['item']

>>> my_list = []
>>> my_list[-3:-3] = ['item']
>>> my_list
['item']

>>> my_list = ['a', 'b']
>>> my_list[5:5] = ['item']
>>> my_list
['a', 'b', 'item']

>>> my_list = ['a', 'b']
>>> my_list[-3:-3] = ['item']
>>> my_list
['item', 'a', 'b']

切片符号与使用slice对象调用__setitem__()方法相同:

The slice notation is the same as calling __setitem__() method with a slice object:

>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list.__setitem__(slice(5, 5), ['item'])
>>> my_list
['a', 'b', 'c', 'd', 'e', 'item', 'f', 'g']

这篇关于Python的insert()方法与通过切片插入之间的实现和性能差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆