CSE 160 Section 6
Midterm Review!
Logistics
Midterm: Friday Oct. 31
Lecture Review: File I/O
File I/O
my_file = open(filepath)
for line_of_text in my_file:
# process line_of_text
my_file.close()
Split
Example:
O
Output:
line_of_text = “you’re going to be amazing”
x = line_of_text.split()
print(x)
[“you’re”, “going”, “to”, “be”, “amazing”]
Split
Example:
O
Output:
line_of_text = “you’re,going,to,be,amazing”
x = line_of_text.split(“,”)
print(x)
[“you’re”, “going”, “to”, “be”, “amazing”]
Lecture Review: Dictionary
Dictionary
Collection of key-value pairs
Dictionary
heights = {"Ella": 68,
"Martin": 72,
"Lilly": 49,
"William": 50,
"Simon": 70}
print(heights["Lilly"]) # 49
print(heights["Wen"]) # KeyError
heights["Wen"] = 63 # Add a key-value pair
heights["Lilly"] = 50 # Update value
print(heights["Lilly"]) # 50
Dictionary
# print out all keys
for key in heights.keys():
print(key)
# print out all values
for value in heights.values():
print(value)
# print out keys and values
for (key, value) in heights.items():
print(key, value)
# another method
for key in heights:
value = heights[key]
print(key, value)
Lecture Review: Nested Structures
Review of nested structures
Nested Structure | Example |
List of lists | Pixel grids |
Dictionaries with lists as values | centroids_dict |
List of dictionaries | Excel data with column headers |
Dictionary of dictionaries | Excel data with row and column headers |
Review of nested structures
Nested Lists
255 | 0 | 255 |
0 | 0 | 255 |
255 | 255 | 255 |
| | |
| | |
| | |
Midterm Review Questions?
Practice Questions
Problem A
Write a function called report_long_lines that takes a string file_name and an integer max_length as arguments. It should return the number of lines that were longer than the given length.You may assume the file name provided describes a file that exists.
Example:
numbers.txt:
one
two
three
four
five
print(report_long_lines(“numbers.txt”, 3)) Output: 3
Solution A
def report_long_lines(file_name, max_length):
num_lines = 0
f = open(file_name, "r")
for line in f:
if len(line) > max_length:
num_lines += 1
close(f)
return num_lines
Problem B
Write code that would loop over this list and create a list of the last names of only the female patients.
Should return ['Chan', 'Ross']
Solution B
female_patients = []
for solo_patient in patients:
if solo_patient[3] == ‘female’:
female_patients.append(solo_patient[1])
print(female_patients)
Problem C
Now write code to restructure the list so that the inner lists each contain all of the data of one type i.e. first name, last name , etc
Should return
[ ['Milos', ‘Delia’, ‘Denise’],
[‘Jones’, ’Chan’, ‘Ross’],
[48, 39, 62],
….
[210, 170, 150]]
Problem C
Now write code to restructure the list so that the inner lists each contain all of the data of one type i.e. first name, last name , etc
new_list = []
For i range(len(patients[0]))
Data_list = []
For patient in patients:
Data_list.append(patient[i])
new_list.append(Data_list)