Page 192 -
P. 192
idle session
Let’s see some other list comprehension examples. Open up your IDLE shell and follow along with these one-liner
transformations.
Start by transforming a list of minutes into a list of seconds:
>>> mins = [1, 2, 3]
>>> secs = [m * 60 for m in mins]
>>> secs Simply multiply the
[60, 120, 180] minute values by 60.
How about meters into feet?
>>> meters = [1, 10, 3]
>>> feet = [m * 3.281 for m in meters] Yes, there are 3.281
>>> feet feet in a meter.
[3.281, 32.81, 9.843]
Given a list of strings in mixed and lowercase, it’s a breeze to transform the strings to UPPERCASE:
>>> lower = ["I", "don't", "like", "spam"]
>>> upper = [s.upper() for s in lower]
>>> upper Every string comes with
['I', "DON'T", 'LIKE', 'SPAM'] the “upper()” method.
Let’s use your sanitize() function to transform some list data into correctly formatted times:
>>> dirty = ['2-22', '2:22', '2.22']
>>> clean = [sanitize(t) for t in dirty] It’s never been so easy to turn something
>>> clean dirty into something clean. §
['2.22', '2.22', '2.22']
It’s also possible to assign the results of the list transformation back onto the original target identifier. This
example transforms a list of strings into floating point numbers, and then replaces the original list data:
>>> clean = [float(s) for s in clean]
>>> clean
The “float()” BIF converts to floating point.
[2.22, 2.22, 2.22]
And, of course, the transformation can be a function chain, if that’s what you need:
>>> clean = [float(sanitize(t)) for t in ['2-22', '3:33', '4.44']]
>>> clean Combining transformations on the data
items is supported, too!
[2.22, 3.33, 4.44]
156 Chapter 5