중복 제거
a = [1,3,4,5,5,5,4,3,2,2,3,3,6,7,8,5,4,3,9]
a_set = set(a)
print(a_set) # 중복제거 {1, 2, 3, 4, 5, 6, 7, 8, 9}
교집합 : &
a = ['사과', '감', '수박', '참외', '딸기']
b = ['사과', '멜론', '청포도', '토마토', '참외']
a_set = set(a)
b_set = set(b)
print(a_set & b_set) # 교집합
합집합 : |
a = ['사과', '감', '수박', '참외', '딸기']
b = ['사과', '멜론', '청포도', '토마토', '참외']
a_set = set(a)
b_set = set(b)
print(a_set | b_set) # 합집합
차집합 : -
student_a = ['물리2','국어','수학1','음악','화학1','화학2','체육']
student_b = ['물리1','수학1','미술','화학2','체육']
a = set(student_a)
b = set(student_b)
print(a - b)
f-string을 사용하면 코드가 간결해짐
scores = [
{'name':'영수','score':70},
{'name':'영희','score':65},
{'name':'기찬','score':75},
{'name':'희수','score':23},
{'name':'서경','score':99},
{'name':'미주','score':100},
{'name':'병태','score':32}
]
for s in scores:
name = s['name']
score = str(s['score'])
print(name + '의 점수는 '+score+'점 입니다.')
print(f'{name}의 점수는 {score}점 입니다.')
# f-string 사용하면 간결해짐
try-except문
people = [
{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27},
{'name': 'bobby'},
{'name': 'red', 'age': 32},
{'name': 'queen', 'age': 25}
]
for person in people:
try:
if person['age'] > 20:
print(person['name'])
except:
print(person['name'], 'error입니다.')
# carry
# ben
# bobby error입니다.
# red
# queen
from 파일명(ex. main_func) import *
불러올 함수
# main_func.py
def say_hi():
print('안녕!')
def say_hi_to(name):
print(f'{name}님 안녕하세요.')
# main_test.py
from main_func import *
say_hi()
say_hi_to('영수')
# 안녕!
# 영수님 안녕하세요.
if문 – 삼항연산자
a = 3
# if a % 2 == 0:
# result = '짝수'
# else:
# result = '홀수'
result = ("짝수" if a%2==0 else "홀수") # 이렇게 한 줄로 작성 가능
print(f'{a}는 {result}입니다.')
for문 - 한방에 써버리기
a_list = [1, 3, 2, 5, 1, 2]
# b_list = []
# for a in a_list:
# b_list.append(a*2)
b_list = [a*2 for a in a_list]
print(b_list)
map
list(map(함수, 리스트))
tuple(map(함수, 튜플))
# 1차 조작
people = [
{'name': 'bob', 'age': 20}, # 한 딕셔너리가 각 person
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27},
{'name': 'bobby', 'age': 57},
{'name': 'red', 'age': 32},
{'name': 'queen', 'age': 25}
]
def check_adult(person):
if person['age'] > 20:
return '성인'
else:
return '청소년'
result = map(check_adult, people)
print(list(result))
# ['청소년', '성인', '청소년', '청소년', '성인', '성인', '성인', '성인']
# 2차 조작
def check_adult(person):
return '성인' if person['age'] > 20 else '청소년'
result = map(check_adult, people)
print(list(result))
# 3차 조작
result = map(lambda x: ('성인' if x['age'] > 20 else '청소년'), people)
print(list(result))
filter
result = filter(lambda x: x['age'] > 20, people)
print(list(result))
함수의 매개변수 (어려우니 당장은 눈으로만 익히기)
def cal(a, b):
return a + 2 * b
print(cal(3, 5))
print(cal(5, 3))
print(cal(a=3, b=5))
print(cal(b=5, a=3)) #어떤 매개변수에 어떤 값을 넣을지 적으니 순서 상관 없음
def cal2(a, b=3):
return a + 2 * b
print(cal2(4)) # 위에서 기본 값으로 고정해놓은 값이 들어옴
print(cal2(4, 2)) # 넣어준 값이 들어감
print(cal2(a=6))
print(cal2(a=1, b=7))
def call_names(*args): # 무제한으로 인수값 받을 수 있음
for name in args:
print(f'{name}야 밥먹어라~')
call_names('철수','영수','희재')
def get_kwargs(**kwargs):
print(kwargs)
get_kwargs(name='bob') # {'name': 'bob'}
get_kwargs(name='john', age='27') # {'name': 'john', 'age': '27'}
예를 들어, 아주 많은 몬스터들의 HP를 관리해야 하면 어떻게 해야할까?
class Monster():
hp = 100
alive = True
def damage(self, attack):
self.hp = self.hp - attack
if self.hp < 0 :
self.alive = False
def status_check(self):
if self.alive:
print('살아있다')
else:
print('죽었다')
# Monster은 클래스 m1, m2는 인스턴스
m1 = Monster()
m1.damage(150)
m1.status_check()
m2 = Monster()
m2.damage(90)
m2.status_check()