Say I've got a list and I want to iterate over the first n
of them. What's the best way to write this in Python?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
The normal way would be slicing:
for item in your_list[:n]:
...
回答2:
I'd probably use itertools.islice
(<- follow the link for the docs), which has the benefit of working with any iterable object.
回答3:
You can just slice the list:
>>> l = [1, 2, 3, 4, 5]
>>> n = 3
>>> l[:n]
[1, 2, 3]
and then iterate on the slice as with any iterable.
回答4:
Python lists are O(1) random access, so just:
for i in xrange(n):
print list[i]