Only index needed: enumerate or (x)range?(只需要索引:枚举还是(x)范围?)
问题描述
如果我只想在循环中使用索引,我应该更好地使用 range/xrange
函数和 len()
If I want to use only the index within a loop, should I better use the range/xrange
function in combination with len()
a = [1,2,3]
for i in xrange(len(a)):
print i
或枚举
?即使我根本不会使用 p
?
or enumerate
? Even if I won't use p
at all?
for i,p in enumerate(a):
print i
推荐答案
我会使用 enumerate
,因为它更通用 - 例如,它适用于可迭代对象和序列,以及仅返回引用的开销到一个对象并不是什么大不了的事 - 虽然 xrange(len(something))
虽然(对我来说)更容易阅读你的意图 - 会破坏不支持 len 的对象
...
I would use enumerate
as it's more generic - eg it will work on iterables and sequences, and the overhead for just returning a reference to an object isn't that big a deal - while xrange(len(something))
although (to me) more easily readable as your intent - will break on objects with no support for len
...
这篇关于只需要索引:枚举还是(x)范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:只需要索引:枚举还是(x)范围?
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01