15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

and split each line up into words, and we can sum up the number of words to get a total like this:<br />

>>> f = open('hhga.txt', 'r')<br />

>>> len([word for line in f for word in line.split()])<br />

91<br />

Let us get a quick total file size:<br />

import os<br />

>>> os.stat('hhga.txt').st_size<br />

499L<br />

Assuming that there is at least one whitespace character in the file, we know that there are fewer than<br />

499 non-whitespace characters in the file. We can sum up the length of each word to arrive at our total:<br />

>>> f.seek(0)<br />

>>> sum([len(word) for line in f for word in line.split()])<br />

408<br />

Note we have to rewind back to the beginning of the file each time through because the iterator<br />

exhausts it. But wow, a non-obfuscated one-liner now does something that used to take many lines of<br />

code to accomplish!<br />

As you can see, list comps support multiple nested for loops and more than one if clause. The full<br />

syntax can be found in the official documentation. You can also read more about list comprehensions in<br />

PEP 202.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!