如何迭代列表的前n个元素?

时间:2022-12-04 19:27:59

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?

假设我有一个列表,我想迭代它们的前n个。在Python中编写此代码的最佳方法是什么?

4 个解决方案

#1


78  

The normal way would be slicing:

通常的方法是切片:

for item in your_list[:n]: 
    ...

#2


20  

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

我可能会使用itertools.islice(< - 跟随文档的链接),这有利于处理任何可迭代对象。

#3


9  

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


2  

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

Python列表是O(1)随机访问,所以只需:

for i in xrange(n):
    print list[i]

#1


78  

The normal way would be slicing:

通常的方法是切片:

for item in your_list[:n]: 
    ...

#2


20  

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

我可能会使用itertools.islice(< - 跟随文档的链接),这有利于处理任何可迭代对象。

#3


9  

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


2  

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

Python列表是O(1)随机访问,所以只需:

for i in xrange(n):
    print list[i]