课程: Advanced Python (2018)

Iterators

- [Instructor] The practice of looping over sequences of values is very common in Python, and there are several built-in methods to help out with this. The term we use to describe this looping is called iteration. And in this exercise we'll see how to use the built-in methods to make iterating over sequences quick and easy. So here in my editor I have the iterators_start.py file in my built-in functions chapter open. And at the top I have two sequences of day name abbreviations in both English and in French. And the first function we'll look at is called iter. It creates an iterable object out of a sequence that you give it. So I'll create an iterator of the English days, and I'll write I = iter(days), and then once I've done that I can access the next item whenever I want using the next function. So what I'll do is I'll write print and then next i. And in fact I'll copy and paste that a few times and I'll save. So now I'll run this. I'll go to the debug view and click on run. And there you can see the first three days being printed out. Now on the surface this may not seem very useful since you can already iterate over lists and such using the for statement. But where iter gets really useful is when you give it a function to use to generate the sequence items. So let me clear the console. And over here in my files I've got a text file with six lines of text in it, and using the iter function I can quickly create an iterator to process each line of text in this file. So I'll add that here. So I'm going to use the open function to open the file. And I'll open in read mode. And we'll call the variable file pointer, and then I'll write for line in iter, and then I'm going to use the file pointer's read line method to generate each value, and then I'm going to pass something called a sentinel value to the iterator. And what I'm going to do is print each line as it comes in. Okay, so let's take a look at what's going on here. I'm using the read line function to generate, or in this case retrieve, the next line in the file. And then the second argument is called a sentinel value. So when it's used in this form, the iter function will call the function that we've provided to generate each value, and when that value that's returned is equal to the sentinel value, the iterator will stop. So in this case the iterator is looking for the empty string, which indicates the end of the file. So I'll comment out these lines here. And I'll save and then I'll run this again. And there you can see that each line of the file is being printed out, and that it comes to a stop after line six because the read line function comes back with an empty string when the file is finished. All right, let's take a look at looping over collections next. So if I wanted to create a simple loop over each of the English day names, that's pretty straightforward, right? I would just write for m in days and then just print m. And then let me comment out the previous example, and so I'll just clear the console and run this, and we can see that that works well. Life, however, is rarely that easy, and I might have a need to generate an index along with the data. So, I mean, okay, I suppose I can do something like this. I can say for m in range, I'll use the range function, and then I'll call the length function to get the number of items in the days, list, and then I can print m, and then days m, right? So I'll save and let's run this again. All right so now I have an index, but I don't wanna start at zero. I wanna start at one so I gotta go back and change that. So I'll write m+1. Okay, and now I'll run it again and now we can see that, okay now the index is fixed. So it works, but just within a couple of minutes I've created a looping construct that's needlessly complex and just kinda hard to read. So this is where the enumerate function can help. Enumerate takes a collection along with an optional starting value and it returns a tuple that contains the index value of the current item along with that item in the collection. So I can simplify my loop to look much better. So what I'm going to do is write for and then i,m in enumerate. And I'll give it days and I'll give it a start value of one. That's what the index will start off at. And then I'll just simply print i,m. And you can see that that accomplishes the same thing but with code that's much easier to read. So let's comment out the previous example, all right? And I'll clear the console and we'll run, and now you can see I've got the same result. So we'll come back to enumerate in just a moment, but now let's take a look at the zip function. Sometimes you need to iterate over multiple sequences at the same time. And the zip function takes any number of sequences and will combine them into a single iterator. So if I wanted to iterate over both the English and French day names at the same time, I would use the zip function and it would look like this. I would say for m in zip days and days French, and I will just print m, and let me comment this out. Okay, so now when I run this you can see that the output is a tuple containing each item in both lists. So this gets really useful when you combine it with the enumerate function. So let's try that. I'll go back and I'll write for i, m in enumerate, and I'll leave zip the way it is. And I'll give it a start of 1. Oh I also need to get the index, right? 'Cause that's what enumerate gives me. So for i and m, and I'll print i, and then m 0, because remember I'm getting a tuple back, and then I'll put in = an then m 1, that's the French version, and I'll write in French. All right, so let's save. Let's clear the console and let's run again. And now when I run the code you can see that we have the index along with the English and French day names paired. Now in case you're wondering what happens if the two sequences aren't the same length, the zip function terminates when the shortest sequence is exhausted. So if I go back and remove the French abbreviation for Saturday, right? So let's just take this guy out and let's save it. And let's run it again. So now you can see that the code is stopping at Friday. So these built-in iteration functions really help clean up your code while providing some very useful utilities. So start using them instead of the basic for loops whenever the need arises.

内容