使用切片(切片表示法)
for count, item in enumerate(contents[:10]):
如果您正在迭代生成器,或者列表中的项目很大并且您不希望创建新列表的开销(就像切片一样),您可以使用来自itertools 模块的islice:
for count, item in enumerate(itertools.islice(contents, 10)):
无论哪种方式,我建议您以一种健壮的方式执行此操作,这意味着将功能包装在一个函数中(就像人们想要使用这样的功能一样 - 实际上,这就是命名函数的原因)
import itertools
def enum_iter_slice(collection, slice):
return enumerate(itertools.islice(collection, slice))
例子:
>>> enum_iter_slice(xrange(100), 10)
<enumerate object at 0x00000000025595A0>
>>> list(enum_iter_slice(xrange(100), 10))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> for idx, item in enum_iter_slice(xrange(100), 10):
print idx, item
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
如果您使用 enumerate 和 count 变量只是为了检查项目索引(以便使用您的方法,您可以退出/中断第 10 个项目的循环。)您不需要枚举,只需使用itertools.islice() 全部作为您的功能。
for item in itertools.islice(contents, 10):