Python列表索引效率 [英] Python List Indexing Efficiency

查看:172
本文介绍了Python列表索引效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关内置python列表对象的快速问题.假设您有一个数字为0-99的列表.您正在编写一个将列表中的最后一项用于其他目的的程序.使用list [-1]比使用list [99]更有效吗?换句话说,无论哪种情况,python都会遍历整个列表吗?

Quick question about the built in python list object. Say you have a list with the numbers 0 - 99. You are writing a program that takes the last item in the list and uses it for some other purpose. Is it more efficient to use list[-1] than to use list[99]? In other words, does python iterate through the whole list in either case?

感谢您的帮助.

推荐答案

Python不会遍历列表以查找特定索引.列表是连续内存中的数组(指向元素的指针),因此查找所需元素始终是简单的乘法和加法.如果有的话,list[-1]会稍微慢一些,因为Python需要在长度上添加负索引以获得 real 索引. (不过,我怀疑它的运行速度显着降低了,因为所有这些操作都是在C中完成的.)

Python does not iterate through lists to find a particular index. Lists are arrays (of pointers to elements) in contiguous memory and so locating the desired element is always a simple multiplication and addition. If anything, list[-1] will be slightly slower because Python needs to add the negative index to the length to get the real index. (I doubt it is noticeably slower, however, because all that's done in C anyway.)

这篇关于Python列表索引效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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