3 len('abc') [1,2,3][2] {'spam':3}['spam']
C:\...\PP4E\Lang> python summer.py 4 table2.txt
[21, 21, 21, 21.0]
Summing with zips and comprehensions
We’ll revisit eval later in this chapter, when we explore expression evaluators. Some-
times this is more than we want—if we can’t be sure that the strings that we run this
way won’t contain malicious code, for instance, it may be necessary to run them with
limited machine access or use more restrictive conversion tools. Consider the following
recoding of the summer function (this is in file summer2.py in the examples package if
you care to experiment with it):
def summer(numCols, fileName):
sums = [0] * numCols
for line in open(fileName): # use file iterators
cols = line.split(',') # assume comma-delimited
nums = [int(x) for x in cols] # use limited converter
both = zip(sums, nums) # avoid nested for loop
sums = [x + y for (x, y) in both] # 3.X: zip is an iterable
return sums
This version uses int for its conversions from strings to support only numbers, and not
arbitrary and possibly unsafe expressions. Although the first four lines of this coding
are similar to the original, for variety this version also assumes the data is separated by
commas rather than whitespace, and runs list comprehensions and zip to avoid the
nested for loop statement. This version is also substantially trickier than the original
and so might be less desirable from a maintenance perspective. If its code is confusing,
try adding print call statements after each step to trace the results of each operation.
Here is its handiwork:
C:\...\PP4E\Lang> type table3.txt
1,5,10,2,1
2,10,20,4,2
3,15,30,8,3
4,20,40,16,4
C:\...\PP4E\Lang> python summer2.py 5 table3.txt
[10, 50, 100, 30, 10]
Summing with dictionaries
The summer logic so far works, but it can be even more general— by making the column
numbers a key of a dictionary rather than an offset in a list, we can remove the need to
pass in a number-columns value altogether. Besides allowing us to associate meaningful
labels with data rather than numeric positions, dictionaries are often more flexible than
lists in general, especially when there isn’t a fixed size to our problem. For instance,
suppose you need to sum up columns of data stored in a text file where the number of
columns is not known or fixed:
String Method Utilities | 1411