- List comprehension
Python Console
# numbers = [1, 2, 3]
# new_list = []
# for n in numbers:
# add_1 = n+1
# new_list.append(add_1)
# print(new_list)
# [new_item for item in list]
numbers = [1, 2, 3]
new_list = [n+1 for n in numbers]
print(new_list)
# [letter for letter in name]
name = "Angela"
letter_list = [letter for letter in name]
print(letter_list)
# [new_item for item in range]
range_list = [num * 2 for num in range(1, 5)]
print(range_list)
# [new_item for item in list if test]
names = ['Alex', 'Beth', 'Caroline', 'Dave', 'Eleanor', 'Freddie']
short_names = [name for name in names if len(name) < 5]
print(short_names)
long_names = [name.upper() for name in names if len(name) > 5]
print(long_names)
- Python Sequences
List
Range
String
Tuple
- Exercise 235 SQUARE numbers
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
# 🚨 Do Not Change the code above 👆
# Write your 1 line code 👇 below:
# [new_item for item in list]
squared_numbers = [n*n for n in numbers]
# Write your code 👆 above:
print(squared_numbers)
C:\Users\MikeK\PycharmProjects\Day_26_List_Comprehension\venv\Scripts\python.exe C:\Users\MikeK\PycharmProjects\Day_26_List_Comprehension\main.py
[1, 1, 4, 9, 25, 64, 169, 441, 1156, 3025]
Process finished with exit code 0
- Exercise 236 Even numbers from a list
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
# 🚨 Do Not Change the code above
# Write your 1 line code 👇 below:
# [new_item for item in list if test]
result = [num for num in numbers if num % 2 == 0]
# Write your code 👆 above:
print(result)
C:\Users\MikeK\PycharmProjects\Day_26_List_Comprehension\venv\Scripts\python.exe C:\Users\MikeK\PycharmProjects\Day_26_List_Comprehension\main.py
[2, 8, 34]
Process finished with exit code 0
- Exercise 237 Data Overlap
main.py
# [new_item for item in list if test]
with open("file1.txt") as file1:
file_1_data = file1.readlines()
with open("file2.txt") as file2:
file_2_data = file2.readlines()
result = [int(num) for num in file_1_data if num in file_2_data]
# Write your code above 👆
print(result)
C:\Users\MikeK\PycharmProjects\Day_26_List_Comprehension\venv\Scripts\python.exe C:\Users\MikeK\PycharmProjects\Day_26_List_Comprehension\main.py
[3, 6, 5, 33, 12, 7, 42, 13]
Process finished with exit code 0
File1.txt
3
6
5
8
33
12
7
4
72
2
42
13
File2.txt
3
6
13
5
7
89
12
3
33
34
1
344
42
Exercise 238 Apply List Comprehension to the US States Game
main.py
import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("50_states.csv")
all_states = data.state.to_list()
guessed_states = []
while len(guessed_states) < 50:
answer_state = screen.textinput(title=f"{len(guessed_states)}/50 States Correct",
prompt="Whats another state's name?").title()
if answer_state == "Exit":
missing_states = [state for state in all_states if state not in guessed_states]
new_data = pandas.DataFrame(missing_states)
new_data.to_csv("states_to_learn.csv")
break
if answer_state in all_states:
guessed_states.append(answer_state)
t = turtle.Turtle()
t.hideturtle()
t.penup()
state_date = data[data.state == answer_state]
t.goto(int(state_date.x), int(state_date.y))
t.write(answer_state)
Exercise 239 Dictionary Comprehension
- new_dict = {new_key:new_value for item in list}
- new_dict = {new_key:new_value for (key, value) in dict.items() if test}
- {new_key:new_value for (index, row) in df.iterrows()}
Python console
Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)] on win32
names = ['Alex', 'Beth', 'Caroline', 'Eleanor', 'Freddie']
import random
students_scores = {student:random.randint(1, 100) for student in names}
- Output
{'Alex': 35, 'Beth': 79, 'Caroline': 62, 'Eleanor': 69, 'Freddie': 64}
passed_students = {student:score for (student, score) in students_scores.items() if score >= 60}
-output
passed_students = {dict: 2} {'Alex': 63, 'Freddie': 96}
'Alex' = {int} 63
'Freddie' = {int} 96
Exercise 240 Dictionary Comprehension 1
You are going to use Dictionary Comprehension to create a dictionary called result that takes each word in the given sentence and calculates the number of letters in each word.
Try Googling to find out how to convert a sentence into a list of words.
Do NOT Create a dictionary directly. Try to use Dictionary Comprehension instead of a Loop.
sentence = "What is the Airspeed Velocity of an Unladen Swallow?"
# Don't change code above 👆
# Write your code below:
result = {word:len(word) for word in sentence.split()}
print(result)
Exercise 241 Dictionary Comprehension 2
You are going to use Dictionary Comprehension to create a dictionary called weather_f that takes each temperature in degrees Celsius and converts it into degrees Fahrenheit.
To convert temp_c into temp_f:
(temp_c * 9/5) + 32 = temp_f
Do NOT Create a dictionary directly. Try to use Dictionary Comprehension instead of a Loop.
Example Output
{
'Monday': 53.6,
'Tuesday': 57.2,
'Wednesday': 59.0,
'Thursday': 57.2,
'Friday': 69.8,
'Saturday': 71.6,
'Sunday': 75.2
}
weather_c = {
"Monday": 12,
"Tuesday": 14,
"Wednesday": 15,
"Thursday": 14,
"Friday": 21,
"Saturday": 22,
"Sunday": 24,
}
# 🚨 Don't change code above 👆
# Write your code 👇 below:
weather_f = {day:temp * 9/5 + 32 for (day, temp) in weather_c.items()}
print(weather_f)
Exercise 242 How to iterate over Pandas data frame
student_dict = {
"student": ["Angela", "James", "Lily"],
"score": [56, 76, 98]
}
# Looping through dictionaries:
#for (key, value) in student_dict.items():
# print(key)
# print(value)
import pandas
student_data_frame = pandas.DataFrame(student_dict)
# print(student_data_frame)
# Loop through a dataframe
# for (key, value) in student_data_frame.items():
# print(key)
# Loop through rows of a data frame
for (index, row) in student_data_frame.iterrows():
print(row)
Exercise 243 Introducing the NATO Project
TODO 1. Create a dictionary in this format:
{"A":"Alpha", "B":"Bravo"}
TODO 2. Create a list of the phonetic code words from a word that the user inputs.
Exercise 244 Solution the NATO Project
# Keyword Method with iterrows()
# {new_key:new_value for (index, row) in df.iterrows()}
import pandas
data_nato = pandas.read_csv("nato_phonetic_alphabet.csv")
# TODO 1. Create a dictionary in this format:
# {"A": "Alfa", "B": "Bravo"}
nato_dict = {row.letter:row.code for (index, row) in data_nato.iterrows()}
# TODO 2. Create a list of the phonetic code words from a word that the user inputs.
word = input("Enter a word: ").upper()
output_list = [nato_dict[letter] for letter in word]
print(output_list)
Top comments (0)