Python - list & dict comprehension
Example 1 - Create a dictionary
Implementation 1: standard
def check_frequency_1 (x ):
frequency = {}
for c in set (x ):
frequency [c ] = x .count (c )
return frequency
numbers = ['a' , 'b' , 'a' , 'd' , 'c' , 'd' , 'b' , 'a' , 'b' ]
print (check_frequency_1 (numbers )) # Output: {'c': 1, 'd': 2, 'a': 3, 'b': 3}
Implementation 2: comprehension
def check_frequency_2 (x ):
return {c : x .count (c ) for c in set (x )}
numbers = ['a' , 'b' , 'a' , 'd' , 'c' , 'd' , 'b' , 'a' , 'b' ]
print (check_frequency_1 (numbers )) # Output: {'c': 1, 'd': 2, 'a': 3, 'b': 3}
Example 2 - Create a list (flask example)
Implementation 1: standard
@app .route ('/person' , methods = ['GET' ])
def get_perosn ():
persons = Person .query .all ()
# create a list
results = []
for person in persons :
results .append (person .serialize ())
return jsonify (results ), 200
Implementation 2: comprehension
@app .route ('/person' , methods = ['GET' ])
def get_perosn ():
persons = Person .query .all ()
# create a list
results = [person .serialize () for person in persons ]
return jsonify (results ), 200
@app .route ('/person' , methods = ['GET' ])
def get_perosn ():
persons = Person .query .all ()
# create a list
results = list (map (lambda person : person .serialize (), persons ))
return jsonify (results ), 200
Example 3 - Create a matrix
Implementation 1: comprehension standard
def matrix_builder_1 (n ):
row = [1 for i in range (0 , n )] # Crea una lista con 'n' 1s
matrix = [row for i in range (0 , n )] # Crea una lista con 'n' columnas
return matrix
Implementation 2: comprehension advanced 1
def matrix_builder_2 (n ):
matrix = [[1 for i in range (0 , n )]
for i in range (0 , n )]
return matrix
Implementation 3: comprehension advanced 2
def matrix_builder_3 (n ):
return [[1 for i in range (n )] for i in range (n )] # Omito el 1er parametro de range()