DAY18: Python day 26
dongdiri
Posted on February 5, 2024
Python list comprehension
- very unique to Python
- an alternative to a
for
loop when working with sequences like list, range, string, tuple -
new_list = [new_item for item in list]
numbers = [1, 2, 3]
new_list = [n+1 for n in numbers]
name = "dongdiri"
character_list = [letter for letter in name]
- also can add an
if
statement
character_list = [letter for letter in name if character != "r"
Dictionary comprehension
- new_dict =
{new_key:new_value for item in list}
or{new_key:new_value for (key, value) in dict.items()}
- be careful not to forget
.items()
Panda .iterrows
- loop through rows of a data frame using panda
{row.new_key:row.new_value for (index, row) in data.iterrows()}
End of the lesson project: NATO alphabet converter
#TODO 1. Create a dictionary in this format:
data = pandas.read_csv("nato_phonetic_alphabet.csv")
new_dict = {row.letter: row.code for (index, row) in data.iterrows()}
#TODO 2. Create a list of the phonetic code words from a word that the user inputs.
name = input("enter a word: ").upper()
code_list = [new_dict[letter] for letter in name]
print(code_list)
Today's content was a bit hard to understand-I should take time to review it as well as python dictionaries.
💖 💪 🙅 🚩
dongdiri
Posted on February 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
privacy Caught in the Crunch My Journey from Snacks to 2 Million Exposed Users Privacy
November 30, 2024