How to iterate over the first n elements of a list

2019-02-01 16:18发布

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?

4条回答
手持菜刀,她持情操
2楼-- · 2019-02-01 16:44

Python lists are O(1) random access, so just:

for i in xrange(n):
    print list[i]
查看更多
放荡不羁爱自由
3楼-- · 2019-02-01 16:47

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楼-- · 2019-02-01 17:03

I'd probably use itertools.islice (<- follow the link for the docs), which has the benefit of working with any iterable object.

查看更多
祖国的老花朵
5楼-- · 2019-02-01 17:09

The normal way would be slicing:

for item in your_list[:n]: 
    ...
查看更多
登录 后发表回答