Skip to content
Snippets Groups Projects
Commit 685071c2 authored by Andy Kuemmel's avatar Andy Kuemmel
Browse files

Deleted f22/andy_lec_notes/lec24_Nov02_Comprehensions/lec24_comprehensions_template.ipynb

parent 4c52155c
No related branches found
No related tags found
No related merge requests found
%% Cell type:code id: tags:
``` python
# Warmup 1: Sort this dictionary by keys
# source: https://en.wikipedia.org/wiki/Big_Ten_Conference#Members (2021)
enrollments = { "Wisconsin": 45540, "Michigan": 47907, "Illinois": 52331,
"Iowa": 30448, "Minnesota": 52017, "Ohio State": 61369, "Northwestern": 22316}
# your answer here:
```
%% Output
{'Illinois': 52331,
'Iowa': 30448,
'Michigan': 47907,
'Minnesota': 52017,
'Northwestern': 22316,
'Ohio State': 61369,
'Wisconsin': 45540}
%% Cell type:code id: tags:
``` python
# wrong way #1a
```
%% Output
['Illinois',
'Iowa',
'Michigan',
'Minnesota',
'Northwestern',
'Ohio State',
'Wisconsin']
%% Cell type:code id: tags:
``` python
# wrong way #1b
```
%% Output
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-a3dbbd71dd1d> in <module>
1 # wrong way #2
----> 2 dict(sorted(enrollments))
ValueError: dictionary update sequence element #0 has length 8; 2 is required
%% Cell type:code id: tags:
``` python
# wrong way #1c
```
%% Output
[('Illinois', 52331),
('Iowa', 30448),
('Michigan', 47907),
('Minnesota', 52017),
('Northwestern', 22316),
('Ohio State', 61369),
('Wisconsin', 45540)]
%% Cell type:code id: tags:
``` python
# correct way:
```
%% Output
{'Illinois': 52331,
'Iowa': 30448,
'Michigan': 47907,
'Minnesota': 52017,
'Northwestern': 22316,
'Ohio State': 61369,
'Wisconsin': 45540}
%% Cell type:code id: tags:
``` python
# Warmup 2: Sort enrollments by values ....use `extract`
print(enrollments)
def extract(s):
return s[-1]
```
%% Output
{'Wisconsin': 45540, 'Michigan': 47907, 'Illinois': 52331, 'Iowa': 30448, 'Minnesota': 52017, 'Ohio State': 61369, 'Northwestern': 22316}
{'Northwestern': 22316,
'Iowa': 30448,
'Wisconsin': 45540,
'Michigan': 47907,
'Minnesota': 52017,
'Illinois': 52331,
'Ohio State': 61369}
%% Cell type:code id: tags:
``` python
# alternate way to do the same thing with lambdas:
```
%% Cell type:code id: tags:
``` python
# Warmup 3: Sort this list of dictionaries by 'name'
volunteers = [ {"name": "Skylar", "hours": 53},
{"name":"Patrice", "hours": 72},
{"name":"Gabriella", "hours": 45},
{"name": "Jayden", "hours": 62} ]
def extract_name(d):
return d['name']
```
%% Output
[{'name': 'Gabriella', 'hours': 45},
{'name': 'Jayden', 'hours': 62},
{'name': 'Patrice', 'hours': 72},
{'name': 'Skylar', 'hours': 53}]
%% Cell type:code id: tags:
``` python
# alternate way with lambda:
```
%% Output
[{'name': 'Gabriella', 'hours': 45},
{'name': 'Jayden', 'hours': 62},
{'name': 'Patrice', 'hours': 72},
{'name': 'Skylar', 'hours': 53}]
%% Cell type:code id: tags:
``` python
# What is a lambda function?
# an abstraction (shortcut) for a function
# remove the def, name, and return statement
# just describe the parameter and the return value
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# Warmup 4: Sort the above list of dictionaries by 'hours'
```
%% Output
[{'name': 'Gabriella', 'hours': 45},
{'name': 'Skylar', 'hours': 53},
{'name': 'Jayden', 'hours': 62},
{'name': 'Patrice', 'hours': 72}]
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# Warmup 5: Sort this lists of strings by length of string
fruits = ["apple", "blueberry", "cherry", "date", "fig", "grapefruit"]
```
%% Output
['fig', 'date', 'apple', 'cherry', 'blueberry', 'grapefruit']
%% Cell type:code id: tags:
``` python
# Warmup 6: Sort this dictionary of lists by length of list
cities_by_county = {"Dane": ["Madison", "Sun Prairie", "Middleton", "Waunakee"],
"Milwaukee": ["Milwaukee", "West Allis", "Wauwatosa"],
"Rock": ["Janesville", "Beloit"],
"Waukesha": ["Brookfield"]}
```
%% Output
{'Waukesha': ['Brookfield'],
'Rock': ['Janesville', 'Beloit'],
'Milwaukee': ['Milwaukee', 'West Allis', 'Wauwatosa'],
'Dane': ['Madison', 'Sun Prairie', 'Middleton', 'Waunakee']}
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## Lecture 25: Comprehensions
Learning Objectives:
- Create list and dictionary comprehensions
%% Cell type:markdown id: tags:
### 25.1 Create list and dictionary comprehensions
Python frequently gives us ways to shorten code
A comprehension is a shortcut to using a for loop
%% Cell type:code id: tags:
``` python
# Given this list what kind of filtered list could we make from it?
# By filtered, think about keeping certain words
fruits = ["apple", "blueberry", "cherry", "DATE", "FIG", "grapefruit"]
# Talk to your partner and come up with different ideas
# just words that all uppercase
# just the lengths of each word
# keep the short words
```
%% Cell type:code id: tags:
``` python
# long way: using a for loop
new_list = []
for w in fruits:
if len(w) > 5:
new_list.append(w)
```
%% Cell type:code id: tags:
``` python
# Do the same thing using a comprehension
# Tip: Write them in reverse, naming the variable last
```
%% Cell type:code id: tags:
``` python
# list of words in fruits that are all uppercase
fruits = ["apple", "blueberry", "cherry", "DATE", "FIG", "grapefruit"]
```
%% Output
['DATE', 'FIG']
%% Cell type:code id: tags:
``` python
# list of just the lengths of each word
```
%% Output
[5, 9, 6, 4, 3, 10]
%% Cell type:code id: tags:
``` python
# list of all the short words, but make them uppercase
```
%% Output
['APPLE', 'DATE', 'FIG']
%% Cell type:code id: tags:
``` python
# list of words that contain the letter "A" or "a"
```
%% Cell type:code id: tags:
``` python
# Given this list of dictionaries, what kind of lists could we make from it?
# Talk to your partner and come up with different ideas
volunteers = [ {"name": "Skylar", "hours": 53},
{"name":"Patrice", "hours": 72},
{"name":"Gabriella", "hours": 45},
{"name": "Jayden", "hours": 62}
]
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# Given this dictionary, what list could we make?
cities_by_county = {"Dane": ["Madison", "Sun Prairie", "Middleton", "Waunakee"],
"Milwaukee": ["Milwaukee", "West Allis", "Wauwatosa"],
"Rock": ["Janesville", "Beloit"],
"Waukesha": ["Brookfield"]}
```
%% Cell type:markdown id: tags:
### The syntax of Comprehensions
%% Cell type:markdown id: tags:
![comprehensions.png](attachment:comprehensions.png)
%% Cell type:markdown id: tags:
### if/else in a comprehension has a different ordering
%% Cell type:code id: tags:
``` python
# If/else...
# convert these Fahrenheit temps to an int in Celsius using C = 5/9 * (F-32)
temps = ["32", "45", "90", "212"]
[5/9 * (int(f)-32) for f in temps]
```
%% Output
[0.0, 7.222222222222222, 32.22222222222222, 100.0]
%% Cell type:code id: tags:
``` python
# do it again, but change empty strings to None
# need to use an if else clause which must come before the 'for'
# new_list = [expression if conditional_expression else alternate_expression for val in iterable ]
temps = ["32", "45", "90", "", "212"]
```
%% Output
[0.0, 7.222222222222222, 32.22222222222222, None, 100.0]
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
### Dictionary Comprehensions
We use a for loop that iterates over dict.items()
We use the concept of 'tuple unpacking' by writing a `for (k,v) in dictname.items()`
%% Cell type:code id: tags:
``` python
scores_dict = {"Bob": [18, 72, 83],
"Cindy" : [27, 11, 55, 73, 87],
"Alice": [16, 33, 42, 89, 90],
"Meena": [39, 93, 9, 3, 55, 72, 19]}
# Create a dictionary where the key is the same, but the value is the max score in each list
{k:v for (k,v) in scores_dict.items()}
```
%% Cell type:code id: tags:
``` python
# Create a dictionary where the key is the same, but the value is the average score
```
%% Cell type:code id: tags:
``` python
# Create a single dictionary where the key is the name and the value is the hours.
volunteers = [ {"name": "Skylar", "hours": 53},
{"name":"Patrice", "hours": 72},
{"name":"Gabriella", "hours": 45},
{"name": "Jayden", "hours": 62} ]
```
%% Output
{'Skylar': 53, 'Patrice': 72, 'Gabriella': 45, 'Jayden': 62}
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# For more reference
# https://www.w3schools.com/python/python_lists_comprehension.asp
# https://www.datacamp.com/community/tutorials/python-dictionary-comprehension
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment