Only index needed: enumerate or (x)range?

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 

or enumerate ? Even if I won't use p at all?

for i,p in enumerate(a):
    print i    

我会使用enumerate因为它更通用 - 例如它可以在迭代和序列上工作,而仅仅返回对象引用的开销并不是什么大不了的事 - 虽然xrange(len(something))虽然(对我来说)按照您的意图更容易读取 - 将不支持len对象打破...


That's a rare requirement – the only information used from the container is its length! In this case, I'd indeed make this fact explicit and use the first version.


Using xrange with len is quite a common use case, so yes, you can use it if you only need to access values by index.

But if you prefer to use enumerate for some reason, you can use underscore (_), it's just a frequently seen notation that show you won't use the variable in some meaningful way:

for i, _ in enumerate(a):
    print i

There's also a pitfall that may happen using underscore (_). It's also common to name 'translating' functions as _ in i18n libraries and systems, so beware to use it with gettext or some other library of such kind (thnks to @lazyr).

链接地址: http://www.djcxy.com/p/23996.html

上一篇: 循环播放内容和索引列表

下一篇: 只需要索引:枚举或(x)范围?