哪一种是最有效的方法来遍历python中的列表? [英] Which is the most efficient way to iterate through a list in python?
本文介绍了哪一种是最有效的方法来遍历python中的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个物品清单:
x = [1, 2, 3, 4, 5]
我需要为每个项目执行一些功能.在某些情况下,我需要返回项目的索引.
I need to perform some functions for each of these items. In a certain case, I need to return the index of an item.
哪种是最好,最有效的方法?
Which is the best and most efficient way?
for item in list:
....
或
for i in range(len(list)):
....
推荐答案
for item in list:
它显然是函数调用较少的那个.
its obviously the one with fewer function calls.
如果您想在旅途中获取项目索引,请使用枚举像这样
If you want to get the index of items as you go use enumerate like this
for pos, item in enumerate(collection):
这篇关于哪一种是最有效的方法来遍历python中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文