여러가지/Python
Day26 - List Comprehension
15June
2024. 5. 14. 00:10
● GIT URL : https://github.com/yooyijun15/Python/tree/main/Day26
● 학습 내용
1) List Comprehension
# 1. 리스트 값 1씩 증가
# 방법 (1)
numbers = [1, 2, 3]
new_list = []
for i in numbers:
add = i + 1
new_list.append(add)
print(new_list)
# 방법 (2) - List Comprehension 활용하여 loof 사용 없이 단순화
numbers = [1, 2, 3]
new_list = [i + 1 for i in numbers]
print(new_list)
# 2. 대문자 변환
name = "Angela"
new_list = [letter.upper() for letter in name]
print(new_list)
names = ["Alex", "Dave", "Eleanor", "Freddie"]
new_list = [name.upper() for name in names]
print(new_list)
# 3. range( , ) 활용
new_list = [i * 2 for i in range(1, 5)]
print(new_list)
2) Conditional List Comprehension
# 4. if 조건절 사용 - Conditional List Comprehension
names = ["Alex", "Dave", "Eleanor", "Freddie"]
new_list = [name for name in names if len(name) < 5]
print(new_list)
ex)
list_of_strings = input().split(',')
# (리스트) 문자 -> 정수 변환
list_of_int = [int(num) for num in list_of_strings]
print(list_of_int)
# 짝수 추출
result = [i for i in list_of_int if i % 2 == 0]
print(result)
ex)
# file1.txt 불러오기
with open("file1.txt") as file_1:
# split() : 파일 리스트로 불러오기
# contents_1 = file_1.read().split()
# readlines() : 한 줄씩 불러오기
contents_1 = file_1.readlines()
# print(contents_1)
# file2.txt 불러오기
with open("file2.txt") as file_2:
contents_2 = file_2.readlines()
# print(contents_2)
# contents_1와 contents_2의 동일한 값 추출
result = [int(i) for i in contents_1 if i in contents_2]
print(result)
3) Dictionary Comprehension
# 5. Dictionary Comprehension
from random import randint
names = ["Alex", "Dave", "Eleanor", "Freddie"]
# new_dict = {new_key:new_value for item in list}
students_score = {student:randint(1, 100) for student in names}
print(students_score)
# 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 test}
passed_students = {student:score for (student, score) in students_score.items() if score >= 60}
print(passed_students)
ex)
sentence = input()
# What is the Airspeed Velocity of an Unladen Swallow?
# list_of_strings = sentence.split()
# result = {word:len(word) for word in list_of_strings}
result = {word:len(word) for word in sentence.split()}
print(result)
ex)
weather_c = eval(input())
# {"Monday": 12, "Tuesday": 14, "Wednesday": 15, "Thursday": 14, "Friday": 21, "Saturday": 22, "Sunday": 24}
# 그대로 불러오기
# weather_f = {day:temp for (day, temp) in weather_c.items()}
weather_f = {day:(temp * 9/5) + 32 for (day, temp) in weather_c.items()}
# (temp_c * 9/5) + 32 = temp_f
print(weather_f)
[참고] for 구문 사용하여 데이터프레임 읽기 및 딕셔너리 변환
index : 데이터프레임의 행 번호
row : 컬럼 값
ex) row.iloc[0] : 첫번째 컬럼
data = pandas.read_csv('nato_phonetic_alphabet.csv')
phonetic_dict = {row.letter:row.code for (index, row) in data.iterrows()}
[참고] 키 [위치/레이블] 취급
# .iloc : 위치 기반 접근
import pandas
data = pandas.read_csv('nato_phonetic_alphabet.csv')
# 딕셔너리 {키: 값, ...} 형식으로 .csv 파일 저장
for (index, row) in data.iterrows():
# (기존) 키 - 위치 취급
# (현재) 키 - 레이블 취급
# (1) 키 - 위치 취급
# 위치 취급 경우 (인덱스 접근) .iloc 사용
# .iloc : 위치 기반 접근
dict_key = row.iloc[0]
dict_value = row.iloc[1]
# (2) 키 - 레이블 취급
dict_key = row["letter"]
dict_value = row["code"]
dictionary[dict_key] = dict_value
4) List Comprehension
import pandas
data = pandas.read_csv('nato_phonetic_alphabet.csv')
# 딕셔너리 {키: 값, ...} 형식으로 .csv 파일 저장
# Dictionary Comprehension
phonetic_dict = {row.letter:row.code for (index, row) in data.iterrows()}
word = input(f"Enter a word: ").upper()
# List Comprehension
out_put_list = [phonetic_dict[each] for each in word]
print(out_put_list)