카테고리 없음

내일배움캠프_파이썬 라이브러리_1회차

iron-min 2025. 9. 25. 20:15

1. 오늘 배운것

1) 리스트 컴프리헨션 (List Comprehension) : for 문을 한줄로 줄여주는 문법

① 기본 구조 : [표현식 for 변수 in 반복가능객체]

won_prices = [13200, 8800, 24500, 50100, 9900] # 원화 가격 (예시)
usd_prices = [price / 1100 for price in won_prices] # 달러 환산

print("원화 가격:", won_prices)
print("달러 환산:", usd_prices)

 

 

② 조건부 리스트 컴프리헨션 : [표현식 for 변수 in 반복가능객체 if 조건]

scores = [68, 73, 88, 95, 61, 79, 84] # 시험 점수
passed = [s for s in scores if s >= 70] # 70점 이상만 추출

print("전체 점수:", scores)
print("통과 점수:", passed)

 

③ 딕셔너리에서 조건 추출

students = [
    {"name": "다은", "age": 21, "grade": "A"},
    {"name": "주원", "age": 20, "grade": "B"},
    {"name": "윤호", "age": 23, "grade": "A"},
    {"name": "하린", "age": 22, "grade": "C"},
]

# grade가 'A'인 학생 이름만 뽑기
a_students = [s["name"] for s in students if s["grade"] == "A"]

print("A등급 학생:", a_students)

 

2) 리스트 슬라이싱 (List Slicing) : 리스트의 특정 부분을 잘라내는 기능

① 문법 : 리스트[start : end : step]

② 예시

numbers = [5, 10, 15, 20, 25, 30, 35]

print(numbers[1:4]) # [10, 15, 20]
print(numbers[:3]) # [5, 10, 15]
print(numbers[3:]) # [20, 25, 30, 35]
print(numbers[::2]) # [5, 15, 25, 35]
print(numbers[::-1]) # [35, 30, 25, 20, 15, 10, 5]

 

 

3) 람다 함수 (Lambda Function) + map / filter

① 문법 : “lambda 매개변수 : 표현식”

# 람다 함수
multiply_lambda = lambda x, y: x * y

print(multiply(4, 6)) # 24
print(multiply_lambda(4, 6)) # 24

 

② map 함수랑 같이쓰기

map의 구조: map(function, iterable) : iterable의 각 원소에 함수를 적용

data = [3, 7, 12, 18, 25]

squares = list(map(lambda x: x**2, data)) # 각 원소 제곱

print("제곱 결과:", squares)

map은 항상 list와 같이 써줘야 하는것 같습니다. 리스트 컴프리헨션도 안되더군요.

 

③ filter 함수랑 같이쓰기

filter의 구조: filter(function, iterable) : function이 True인 원소만 남김

odds = list(filter(lambda x: x % 2 == 1, data)) # 홀수만 필터링

print("홀수만:", odds)

④ map + filter 조합

# 홀수만 뽑아서 3배로 만들기
tripled_odds = list(map(lambda x: x * 3, filter(lambda x: x % 2 == 1, data)))

print("홀수 3배:", tripled_odds)