DAY18: Python day 26

dongdiri

dongdiri

Posted on February 5, 2024

DAY18: Python day 26

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]
Enter fullscreen mode Exit fullscreen mode
  • also can add an if statement
character_list = [letter for letter in name if character != "r"
Enter fullscreen mode Exit fullscreen mode

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()}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Today's content was a bit hard to understand-I should take time to review it as well as python dictionaries.

💖 💪 🙅 🚩
dongdiri
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