I'd like to iterate two different iterators, something like this:
file1 = open('file1', 'r') file2 = open('file2', 'r') for item in one_then_another(file1, file2): print item
Which I'd expect to print all the lines of file1, then all the lines of file2.
I'd like something generic, as the iterators might not be files, this is just an example. I know I could do this with:
for item in [file1]+[file2]:
but this reads both files into memory, which I'd prefer to avoid.
Use the izip() Function to Iterate Over Two Lists in Python It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.
You can process adjacent items from the lists by using itertools. zip_longest() ( itertools. izip_longest() if using Python 2) to produce a sequence of paired items. Pairs will be padded with None for lists of mismatched length.
There are two types of iteration: Definite iteration, in which the number of repetitions is specified explicitly in advance. Indefinite iteration, in which the code block executes until some condition is met.
Use itertools.chain
:
from itertools import chain for line in chain(file1, file2): pass
fileinput
module also provides a similar feature:
import fileinput for line in fileinput.input(['file1', 'file2']): pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With