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 个解决方案
#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
#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]