Tutorial on Python Iterators and Generators
0
komentar
What Are Iterators? Why Use Them? Let’s start with an example we know from our unit on Python file and directory programming (http: //heather.cs.ucdavis.edu/˜matloff/Python/PyFileDir.pdf). Say we open a file and assign the result to f, e.g. f = open(’x’) Suppose we wish to print out the lengths of the lines of the file. for l in f.readlines(): print len(l) But the same result can be obtained with for l in f: print len(l) The second method has two advantages: (a) it’s simpler and more elegant (b) a line of the file is not read until it is actually needed For point (b), note that typically this becomes a major issue if we are reading a huge file, one that either might not fit into even virtual memory space, or is big enough to cause performance issues, e.g. excessive paging. Point (a) becomes even clearer if we take the functional programming approach. The code print map(len,f.readlines()) is not as nice as print map(len,f).
Point (b) would be of major importance if the file were really large. The first method above would have the entire file in memory, very undesirable. Here we read just one line of the file at a time. Of course, we also could do this by calling readline() instead of readlines(), but not as simply and elegantly, i.e. we could not use map(). In our second method, f is serving as an iterator. Let’s look at the concept more generally. Recall that a Python sequence is roughly like an array in most languages, and takes on two forms—lists and tuples.1 Sequence operations in Python are much more flexible than in a language like C or C++. One can have a function return a sequence; one can slice sequences; one can concatenate sequences; etc. Download free Tutorial on Python Iterators and Generators here
Point (b) would be of major importance if the file were really large. The first method above would have the entire file in memory, very undesirable. Here we read just one line of the file at a time. Of course, we also could do this by calling readline() instead of readlines(), but not as simply and elegantly, i.e. we could not use map(). In our second method, f is serving as an iterator. Let’s look at the concept more generally. Recall that a Python sequence is roughly like an array in most languages, and takes on two forms—lists and tuples.1 Sequence operations in Python are much more flexible than in a language like C or C++. One can have a function return a sequence; one can slice sequences; one can concatenate sequences; etc. Download free Tutorial on Python Iterators and Generators here
0 komentar:
Post a Comment