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

Update...

Update f22/andy_lec_notes/lec24_Nov02_Comprehensions/.ipynb_checkpoints/lec_24_850-checkpoint.ipynb, f22/andy_lec_notes/lec24_Nov02_Comprehensions/CS220_Lec24_Sec004_Worksheet_Solution.ipynb, f22/andy_lec_notes/lec24_Nov02_Comprehensions/lec24_comprehensions_template.ipynb, f22/andy_lec_notes/lec24_Nov02_Comprehensions/readme.md
Deleted f22/andy_lec_notes/lec_24/lec24_comprehensions_complete.ipynb
parent 4ab16493
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
sorted(enrollments)
```
%% Output
['Illinois',
'Iowa',
'Michigan',
'Minnesota',
'Northwestern',
'Ohio State',
'Wisconsin']
%% Cell type:code id: tags:
``` python
# wrong way #1b
dict(sorted(enrollments))
```
%% 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
sorted(enrollments.items())
```
%% Output
[('Illinois', 52331),
('Iowa', 30448),
('Michigan', 47907),
('Minnesota', 52017),
('Northwestern', 22316),
('Ohio State', 61369),
('Wisconsin', 45540)]
%% Cell type:code id: tags:
``` python
# correct way:
dict(sorted(enrollments.items()))
```
%% 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
print(enrollments)
#def extract(s):
# return s[-1]
dict(sorted(enrollments.items(), key=lambda s: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:
```
%% Output
[('Illinois', 52331),
('Iowa', 30448),
('Michigan', 47907),
('Minnesota', 52017),
('Northwestern', 22316),
('Ohio State', 61369),
('Wisconsin', 45540)]
%% 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(d):
return d['name']
sorted(volunteers, key = extract) # or you can use a lambda ... see below
```
%% 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:
sorted(volunteers, key = lambda thing:thing['name'])
```
%% 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'
sorted(volunteers, key = lambda d:d['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"]
sorted(fruits, key = lambda f:len(f))
```
%% 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"]}
dict(sorted(cities_by_county.items(), key = lambda t: len(t[-1])))
```
%% 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
# let's make some list comprehensions
# Tip: Write them in reverse, naming the variable last
```
%% Cell type:code id: tags:
``` python
# list of words that are all uppercase
fruits = ["apple", "blueberry", "cherry", "DATE", "FIG", "grapefruit"]
[w for w in fruits if w.upper() == w]
```
%% Output
['DATE', 'FIG']
%% Cell type:code id: tags:
``` python
# just the lengths of each word
[len(w) for w in fruits]
```
%% Output
[5, 9, 6, 4, 3, 10]
%% Cell type:code id: tags:
``` python
# keep the short words but make them uppercase
[w.upper() for w in fruits if len(w) < 6]
```
%% Output
['APPLE', 'DATE', 'FIG']
%% 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
# just the names of people who have >60 hours
[d['name'] for d in volunteers if d['hours'] > 60]
```
%% Output
['Patrice', 'Jayden']
%% Cell type:code id: tags:
``` python
# just the hours
```
%% 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"]}
# try something on your own
```
%% 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"]
[5/9 * (int(f)-32) if f != "" else None for f in temps]
```
%% 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:sum(v)/len(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
{k:sum(v)/len(v) for (k,v) in scores_dict.items()}
```
%% Output
{'Bob': 57.666666666666664,
'Cindy': 50.6,
'Alice': 54.0,
'Meena': 41.42857142857143}
%% 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} ]
{d['name']:d['hours'] for d in volunteers}
```
%% 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