只需要索引:枚举或(x)范围? [英] 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)范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文