Deductive comprehensions (also known as analytical expressions) are a unique feature of python. A comprehension is a structure that can construct a new sequence of data from one sequence of data. There are three derivations, supported in both python2 and 3:
.list comprehension
.dictionary comprehension
.set comprehension
A list comprehension
1. Use [] to generate a list
[expression for variable in list] or [expression for variable in list if condition]
Example 1: List of numbers divisible by 3
numbers = [] for x in range(100): if x % 3 == 0: numbers.append(x)
Implementation using derivation
numbers = [x for x in range(100) if x % 3 == 0]
Example 2:
def squared(x): return x*x multiples = [squared(i) for i in range(30) if i % 3 is 0] print multiples # Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
2. Use () to generate generator
Change the [] of the two table derivations to () to get the generator --yeild
multiples = (i for i in range(30) if i % 3 is 0) print(type(multiples)) # Output: <type 'generator'>
2. Dictionary derivation
Dictionary comprehension is similar to list comprehension, except that the square brackets are replaced by curly brackets. direct example
Example 1: Quickly replace key and value
mcase = {'a': 10, 'b': 34} mcase_frequency = {v: k for k, v in mcase.items()} print mcase_frequency # Output: {10: 'a', 34: 'b'}
Example 2: uppercase and lowercase key merging
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3} mcase_frequency = { k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys() if k.lower() in ['a','b'] } print mcase_frequency # Output: {'a': 17, 'b': 34}
Three, set derivation
They are also similar to list comprehensions. The only difference is that it uses curly braces {}.
Example 1:
squared = {x**2 for x in [1, 1, 2]} print(squared) # Output: set([1, 4])
Example 1: Deriving a collection of string lengths with a collection
strings = ['a','is','with','if','file','exception'] {len(s) for s in strings} #If there are {} with the same length, only one [] will be left, which is actually very useful # Output: set([1, 2, 4, 9])
practise:
0 to the power of 9:
squares = [] for x in range(10): squares.append(x**2)
Implementation using derivation
squares = [x**2 for x in range(10)]
1: Convert word length greater than 3 to uppercase output
names = ['bob','tom','alice','jerry','wendy','smith'] print([name.upper() for name in names if len(name)>3])
2: Find (x, y) where x is an even number between 0-5 and y is a list of tuples consisting of odd numbers between 0-5
[(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]
3: Find the list of 3, 6, 9 in m
m = [[1,2,3],[4,5,6],[7,8,9]] [row[2] for row in m] #or [m[row][2] for row in (0,1,2)]
4: Find the list of slashes 1, 5, and 9 in m
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] [m[i][i] for i in range(len(m))]
5: Find the product of each element of the matrix in m and n
m = [[1,2,3],[4,5,6],[7,8,9]] n = [[2,2,2],[3,3,3],[4,4,4]] [m[row][col]*n[row][col] for row in range(3) for col in range(3)] [[m[row][col]*n[row][col] for col in range(3)] for row in range(3)] [[m[row][col]*n[row][col] for row in range(3)] for col in range(3)]
6: Combine the elements of two lists, if the elements are not equal
combs = [] for x in [1,2,3]: for y in [3,1,4]: if x != y: combs.append((x, y)) #derivation [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]7:
create a list of 2-tuples like (number, square) [(x, x**2) for x in range(6)]