This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp
I will post some notes to motivate myself to finish this challenge.
The regular way to create a new list from an existing list
The example below is the regular way to create a new list calculated from an existing list.
Ex:
list = [1, 2, 3]
new_list = []
# Go through each item of the existing list
for num in list:
# With some logic to get the new value
new_value = num + 1
# Append the new value to new_list
new_list.append(new_value)
print(f"old list: {list}")
print(f"new list: {new_list}")
Result:
old list: [1, 2, 3]
new list: [2, 3, 4]Using List Comprehension
List comprehensions provides a concise way to create lists.
* new_list = [new_item for item in list]
Ex:
list = [1, 2, 3]
new_list = [item + 1 for item in list]
print(f"old list: {list}")
print(f"new list: {new_list}")
Result:
old list: [1, 2, 3]
new list: [2, 3, 4]List Comprehension is not only for List
It can be used with python sequence (an ordered set)
* list
* range
* string
* tuple
Ex: range
# get sequence 1, 2, 3, 4 from range(1, 5)
# and double the value
new_list = [number * 2 for number in range(1, 5)]
print(f"new_list: {new_list}")
Result:
new_list: [2, 4, 6, 8]
Ex: string
name = "Frank"
letter_list = [letter for letter in name]
print(f"letter_list: {letter_list}")
Result:
letter_list: ['F', 'r', 'a', 'n', 'k']
Conditional List Comprehension
We can even add some conditions in List Comprehension for filtering.
* new_list = [new_item for item in list if condition]
Ex:
number_list = [1, 2, 3, 4, 5, 6]
even_number_list = [num for num in number_list if num % 2 == 0]
print(f"even_number_list: {even_number_list}")
Result:
even_number_list: [2, 4, 6]
Exp - Get the common numbers from two files
Ex:
# file1.txt and file2.txt contain a bunch of numbers,
# each number on a new line.
# Create a list called result which contains the numbers
# that are common in both files.
with open("file1.txt", encoding="utf-8") as file:
file_1 = file.readlines()
with open("file2.txt", encoding="utf-8") as file:
file_2 = file.readlines()
result = [int(f1) for f1 in file_1 if f1 in file_2]
print(result)
Exp - Refactor the previous US State game
Ex: Previous version
# Define a dictionary
output_disc = {"state": []}
for state in states_list:
if state not in correct_guess_states_list:
output_disc["state"].append(state)
Ex: Using List Comprehension
output_disc = {
"state": [
state for state in states_list if
state not in correct_guess_states_list
]
}
Dictionary Comprehension
* new_dict = {new_key:new_value for item in list}
* new_dict = {new_key:new_value for (key, value) in dict.items()}
* new_dict = {new_key:new_value for (key, value) in dict.items() if condition}
Ex: Generate a dictionary based on a student list to generate student score randomly
import random
students = ["Andy", "Ben", "Calvin"]
# Generate a dictionary from a list
student_scores = {student: random.randint(50, 80) for student in students}
print(f"student_scores: {student_scores}")
Result:
student_scores: {'Andy': 79, 'Ben': 62, 'Calvin': 71}
Ex: Based on the previous example, generate a dictionary to filter out the students whose score is under 60
import random
students = ["Andy", "Ben", "Calvin"]
# Generate a dictionary from a list
student_scores = {student: random.randint(50, 80) for student in students}
# Generate a dictionary from an existing dict with condition
passed_students = {
name: score for (name, score) in student_scores.items() if score >= 60
}
print(f"student_scores: {student_scores}")
print(f"passed_students: {passed_students}")
Result:
student_scores: {'Andy': 62, 'Ben': 52, 'Calvin': 62}
passed_students: {'Andy': 62, 'Calvin': 62}
Project - NATO Alphabet
Ex:
import pandas
# Using pandas to read csv file
nato_phonetic_alphabet_data_frame =
pandas.read_csv("nato_phonetic_alphabet.csv")
# Generate a dictionary to use alphabet as a key and
# relating word as a value
# {"A": "Alfa", "B": "Bravo"}
nato_phonetic_alphabet_dict = {
row["letter"]: row["code"]
for (index, row) in nato_phonetic_alphabet_data_frame.iterrows()
}
# Ask Users to enter a word
user_input = input("Enter a word? ")
# Use List Comprehension to create a result list
# Loop through all letters of user input and
# get the mapping word by dictionary
result = [nato_phonetic_alphabet_dict[letter] for letter in
user_input.upper()]
print(result)
Result:
Enter a word? Frank
['Foxtrot', 'Romeo', 'Alfa', 'November', 'Kilo']
No comments:
Post a Comment