Online Book Reader

Home Category

Learning Python - Mark Lutz [196]

By Root 1519 0
4

5 [6, 7] 8

In practice, this approach might be used to pick out multiple columns from rows of data represented as nested sequences. In Python 2.X starred names aren’t allowed, but you can achieve similar effects by slicing. The only difference is that slicing returns a type-specific result, whereas starred names always are assigned lists:

>>> for all in [(1, 2, 3, 4), (5, 6, 7, 8)]: # Manual slicing in 2.6

... a, b, c = all[0], all[1:3], all[3]

... print(a, b, c)

...

1 (2, 3) 4

5 (6, 7) 8

See Chapter 11 for more on this assignment form.

Nested for loops

Now let’s look at a for loop that’s a bit more sophisticated than those we’ve seen so far. The next example illustrates statement nesting and the loop else clause in a for. Given a list of objects (items) and a list of keys (tests), this code searches for each key in the objects list and reports on the search’s outcome:

>>> items = ["aaa", 111, (4, 5), 2.01] # A set of objects

>>> tests = [(4, 5), 3.14] # Keys to search for

>>>

>>> for key in tests: # For all keys

... for item in items: # For all items

... if item == key: # Check for match

... print(key, "was found")

... break

... else:

... print(key, "not found!")

...

(4, 5) was found

3.14 not found!

Because the nested if runs a break when a match is found, the loop else clause can assume that if it is reached, the search has failed. Notice the nesting here. When this code runs, there are two loops going at the same time: the outer loop scans the keys list, and the inner loop scans the items list for each key. The nesting of the loop else clause is critical; it’s indented to the same level as the header line of the inner for loop, so it’s associated with the inner loop, not the if or the outer for.

Note that this example is easier to code if we employ the in operator to test membership. Because in implicitly scans an object looking for a match (at least logically), it replaces the inner loop:

>>> for key in tests: # For all keys

... if key in items: # Let Python check for a match

... print(key, "was found")

... else:

... print(key, "not found!")

...

(4, 5) was found

3.14 not found!

In general, it’s a good idea to let Python do as much of the work as possible (as in this solution) for the sake of brevity and performance.

The next example performs a typical data-structure task with a for—collecting common items in two sequences (strings). It’s roughly a simple set intersection routine; after the loop runs, res refers to a list that contains all the items found in seq1 and seq2:

>>> seq1 = "spam"

>>> seq2 = "scam"

>>>

>>> res = [] # Start empty

>>> for x in seq1: # Scan first sequence

... if x in seq2: # Common item?

... res.append(x) # Add to result end

...

>>> res

['s', 'a', 'm']

Unfortunately, this code is equipped to work only on two specific variables: seq1 and seq2. It would be nice if this loop could somehow be generalized into a tool you could use more than once. As you’ll see, that simple idea leads us to functions, the topic of the next part of the book.

* * *

Why You Will Care: File Scanners


In general, loops come in handy anywhere you need to repeat an operation or process something more than once. Because files contain multiple characters and lines, they are one of the more typical use cases for loops. To load a file’s contents into a string all at once, you simply call the file object’s read method:

file = open('test.txt', 'r') # Read contents into a string

print(file.read())

But to load a file in smaller pieces, it’s common to code either a while loop with breaks on end-of-file, or a for loop. To read by characters, either of the following codings will suffice:

file = open('test.txt')

while True:

char = file.read(1) # Read by character

if not char: break

print(char)

for char in open('test.txt').read():

print(char)

The for loop here also processes each character, but it loads the file into memory all at once (and assumes it fits!). To read by lines or blocks instead, you can use while loop code like this:

file = open('test.txt')

Return Main Page Previous Page Next Page

®Online Book Reader