Python 3home |
Introduction to Python
davidbpython.com
Set comparisons make it easy to compare 2 sets for membership.
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print(set_a.union(set_b)) # {1, 2, 3, 4, 5, 6} (set_a + set_b)
print(set_a.difference(set_b)) # {1, 2} (set_a - set_b)
print(set_a.intersection(set_b)) # {3, 4} (what is common between them?)
Ex. 9.15 - 9.17
List comprehensions build a new list based on an existing list.
This list comprehension doubles each value in the nums list
nums = [1, 2, 3, 4, 5]
dblnums = [ val * 2 for val in nums ]
# transform 'for' loop
print(dblnums) # [2, 4, 6, 8, 10]
Ex. 9.18
List comprehensions can also select values to place in the new list.
This list comprehension selects only those values above 35 degrees Celsius:
daily_temps = [26.1, 31.0, 38.4, 36.1, 38.3, 34.1, 32.7, 33.3]
hitemps = [ t for t in daily_temps if t > 35 ]
# transform 'for' loop filter
print(hitemps) # [37.4, 36.1, 38.3]
Ex. 9.19
We can choose to filter or transform or both.
This list comprehension selects values above 35C and converts them to Fahrenheit:
daily_temps = [26.1, 31.0, 38.4, 36.1, 38.3, 34.1, 32.7, 33.3]
f_hitemps = [ round((t * 9/5) + 32, 1) for t in daily_temps if t > 35 ]
# transform 'for' loop filter
print(f_hitemps) # [37, 36, 37]
Ex. 9.19
List comprehensions are a powerful convenience, but not ever required.
Some common operations can be accomplished in a single line. In this example, we produce a list of lines from a file, stripped of whitespace.
stripped_lines = [ i.rstrip() for i in open('pyku.txt').readlines() ]
We can even combine expressions for some fancy footwork
totals = [ float(i.split(',')[2])
for i in open('revenue.csv')
if i.split(',')[1] == 'NY' ]
This last example borders on the overcomplicated -- if we are trying to do too much with a list comprehension, we might be better off with a conventional 'for' loop.
A list comprehension is a single statement.
Since dicts can be converted to and from 2-item tuples, we can manipulate them using list comprehensions.
Recall that dict .items() returns a list of 2-item tuples, and that the dict() constructor uses the same 2-item tuples to build a dict.
mydict = {'a': 5, 'b': 1, 'c': -3}
# dict -> list of tuples
my_items = list(mydict.items()) # list, [('a', 5), ('b', 1), ('c', -3)]
# list of tuples -> dict
mydict2 = dict(my_items) # dict, {'a':5, 'b':1, 'c':-3}
Here's an example: filtering a dictionary by value - accepting only those pairs whose value is larger than 0:
mydict = {'a': 5, 'b': 1, 'c': -3}
filtered_dict = dict([ (i, j)
for (i, j) in mydict.items()
if j > 0 ])
# {'a': 5, 'b': 1}