python list 切片 复杂度,python列表函数的运行时复杂度是多少?

本文探讨了Python列表操作的实现原理及时间复杂度,包括索引访问、末尾弹出、开头弹出、列表扩展等。通过实例发现,直接使用索引访问在大数据量时性能下降。建议使用`enumerate`优化循环中的索引获取。详细信息可见Python Wiki的相关表格。
摘要由CSDN通过智能技术生成

I was writing a python function that looked something like this

def foo(some_list):

for i in range(0, len(some_list)):

bar(some_list[i], i)

so that it was called with

x = [0, 1, 2, 3, ... ]

foo(x)

I had assumed that index access of lists was O(1), but was surprised to find that for large lists this was significantly slower than I expected.

My question, then, is how are python lists are implemented, and what is the runtime complexity of the following

Indexing: list[x]

Popping from the end: list.pop()

Popping from the beginning: list.pop(0)

Extending the list: list.append(x)

For extra credit, splicing or arbitrary pops.

解决方案

there is a very detailed table on python wiki which answers your question.

However, in your particular example you should use enumerate to get an index of an iterable within a loop. like so:

for i, item in enumerate(some_seq):

bar(item, i)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值