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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Python lists are O(1) random access, so just:
You can just slice the list:
and then iterate on the slice as with any iterable.
I'd probably use
itertools.islice
(<- follow the link for the docs), which has the benefit of working with any iterable object.The normal way would be slicing: