It cuts down on the amount of typing and it just makes the code a lot shorter, and in most cases, a lot easier to read.
For Loop
numbers = [1, 2, 3]
new_list = []
for n in numbers:
add_1 = n + 1
new_list.append(add_1)
List Comprehension
numbers = [1, 2, 3]
new_list = [n + 1 for n in numbers]
출력값은 [2, 3, 4]
로 동일함
Conditional List Conprehension
new_list = [new_item for item in list if test]
python console
names = ['Alex', 'Beth', 'Caroline', 'Dave', 'Eleanor', 'Freddie']
short_names = [name for name in names if len(name) < 5]
upper_name = [name.upper() for name in names if len(name) > 5]
#output
['Alex', 'Beth', 'Dave']
['CAROLINE', 'ELEANOR', 'FREDDIE']
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
squared_numbers = [n**2 for n in numbers]
print(squared_numbers)
#output
[1, 1, 4, 9, 25, 64, 169, 441, 1156, 3025]
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
result = [n for n in numbers if n % 2 == 0]
print(result)
#output
[2, 8, 34]
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
main.py
with open("file1.txt") as file1:
f1 = file1.readlines()
with open("file2.txt") as file2:
f2 = file2.readlines()
result = [int(num) for num in f1 if num in f2]
print(result)
#output
[3, 6, 5, 33, 12, 7, 42, 13]
new_dict = {new_key:new_value for item in list}
new_dict = {new_key:new_value for (key,value) in dict.items() if test}
(key,value)
: ,
를 :
로 입력하지 않도록 주의
.split()
sentence = "What is the Airspeed Velocity of an Unladen Swallow?"
result = {word:len(word) for word in sentence.split()}
print(result)
#output
{'What': 4, 'is': 2, 'the': 3, 'Airspeed': 8, 'Velocity': 8, 'of': 2, 'an': 2, 'Unladen': 7, 'Swallow?': 8}
Exercise
weather_c = {
"Monday": 12,
"Tuesday": 14,
"Wednesday": 15,
"Thursday": 14,
"Friday": 21,
"Saturday": 22,
"Sunday": 24,
}
weather_f = {day:temp * 9/5 + 32 for (day,temp) in weather_c.items()}
print(weather_f)
#output
{'Monday': 53.6, 'Tuesday': 57.2, 'Wednesday': 59.0, 'Thursday': 57.2, 'Friday': 69.8, 'Saturday': 71.6, 'Sunday': 75.2}
.item()
: ()
(parnethese) 빼먹지 않게 주의 하기
.iterrows()
for (index, row) in student_data_frame.iterrows():
if row.student == "Amy":
print(row.score)
#output
87
import pandas
#TODO 1. Create a dictionary in this format:
nato = pandas.read_csv("nato_phonetic_alphabet.csv")
final_nato = {nato.letter[n]: nato.code[n] for n in range(0, 26)}
# Angela's solution
# final_nato = {row.letter: row.code for (index, row) in nato.iterrows()}
#TODO 2. Create a list of the phonetic code words from a word that the user inputs.
entered_word = input("Enter a word: ").upper()
nato_word = [final_nato[letter] for letter in entered_word]
print(nato_word)