251001 TIL
2025. 10. 1. 18:12ㆍCourses/아이티윌 오라클 DBA 과정
컬렉션 (Cont.)
Dictionary
# 연속형 자료형
# Dictionary 딕셔너리
# -> 이름(key, name)과 값(value)의 쌍으로 데이터를 정의하는 구조
# -> 순서가 없다
# -> {key:value, key:value, ...}
dic = {"name": "무궁화", "phone": "123-4567", "birth": "202510101"}
print(dic) # {'name': '무궁화', 'phone': '123-4567', 'birth': '202510101'}
print(type(dic)) # <class 'dict'>
print(dic["name"]) # 무궁화
print(dic["phone"]) # 123-4567
dic["name"] = "라일락"
print(dic["name"]) # 라일락
# 삭제
del dic["birth"]
print(dic) # {'name': '라일락', 'phone': '123-4567'}
data = {"msg": "Hello", "msg": "World", "msg": "Python"}
print(data) # {'msg': 'Python'}
# 딕셔너리는 리스트와 다르게 자료의 순서가 중요하지 않다
# key는 정수형으로도 지정 가능(리스트와 혼동될 수 있으므로 권장하지 않음)
rank = {0: "Python", 30: "Java", 10: "Oracle"}
print(rank[0]) # Python
print(rank[30]) # Java
print(rank[10]) # Oracle
######################################################################
# 1) 딕셔너리의 계층 구조
# -> 딕셔너리는 리스트나 다른 딕셔너리를 포함할 수 있다.
# -> 정보를 계층화해서 표현 가능하다
addr = ["서울", "서초구", "강남대로"]
grade = {"korean": 10, "math": 20, "english": 30}
member = {"userid": "Python", "age": 2, "addr": addr, "grade": grade}
print(member)
# 계층화된 값에 접근하기
print(member["addr"][0]) # 서울
print(member["grade"]["korean"]) # 10
# 2) 딕셔너리의 계층화 직접 표현
mydic = {
"total": 2025,
"city": ["서울", "제주", "부산"],
"population": [100, 200, 300],
"date": {"yy": 2025, "mm": 8, "dd": 25},
}
print(mydic)
print(mydic["city"][0]) # 서울
print(mydic["population"][0]) # 100
print(mydic["date"]["yy"]) # 2025
# 3) 리스트의 요소가 딕셔너리가 되는 경우 -> 표 자료형
grade = [
{"name": "홍길동", "kor": 10, "eng": 40},
{"name": "무궁화", "kor": 20, "eng": 60},
{"name": "라일락", "kor": 30, "eng": 90},
]
style = "{}의 국어점수:{}, 영어점수:{}"
print(style.format(grade[0]["name"], grade[0]["kor"], grade[0]["eng"]))
# 홍길동의 국어점수:10, 영어점수:40
print(style.format(grade[1]["name"], grade[1]["kor"], grade[1]["eng"]))
# 무궁화의 국어점수:20, 영어점수:60
print(style.format(grade[2]["name"], grade[2]["kor"], grade[2]["eng"]))
# 라일락의 국어점수:30, 영어점수:90
######################################################################
# 딕셔너리 관련 함수
dic = {"name": "무궁화", "phone": "123-4567", "birth": "202510101"}
print(dic)
# 특정 key에 대응하는 값 얻기
# -> dic["name"] 과 동일
print(dic["name"])
print(dic.get("name"))
# 존재하지 않는 key 에 접근하는 경우
# print(dic["age"]) # KeyError: 'age'
print(dic.get("age")) # None
dic["addr"] = "Seoul"
print(dic["addr"])
print(dic)
# get함수는 전달하는 key가 존재하지 않을 경우
# 대신 반환될 값을 함께 설정할 수 있다
print(dic.get("age", 25)) # 25
keys = dic.keys()
print(keys) # dict_keys(['name', 'phone', 'birth', 'addr'])
key_list = list(keys)
print(key_list) # ['name', 'phone', 'birth', 'addr']
print(key_list[1]) # phone
values = dic.values()
print(values) # dict_values(['무궁화', '123-4567', '202510101', 'Seoul'])
value_list = list(values)
print(value_list) # ['무궁화', '123-4567', '202510101', 'Seoul']
print(value_list[1]) # 123-4567
# key-value를 쌍으로 묶은 튜플들의 모음인 items 객체 얻기
items = dic.items()
print(items)
# dict_items([('name', '무궁화'), ('phone', '123-4567'), ('birth', '202510101'), ('addr', 'Seoul')])
items_list = list(items)
print(items_list)
# [('name', '무궁화'), ('phone', '123-4567'), ('birth', '202510101'), ('addr', 'Seoul')]
print(items_list[1]) # ('phone', '123-4567')
DateTime
# 시스템의 현재 날짜 정보 조회하기
import datetime as dt
# 현재 날짜(년월일시분초) 정보 가져오기
today = dt.datetime.now()
print(today) # 2025-10-01 11:48:07.155920
print(today.year) # 2025
print(today.month) # 10
print(today.day) # 1
print(today.hour) # 11
print(today.minute) # 48
print(today.second) # 07
print(today.microsecond) # 155920
# 요일 반환 0(월) 1(화) 2(수) 3(목) 4(금) 5(토) 6(일)
print(today.weekday()) # 2 -> 수요일
# 요일 이름 출력
days = ("월", "화", "수", "목", "금", "토", "일") # 튜플
print(days[today.weekday()])
# 출력 형식 만들기
print(today.strftime("%y/%m/%d %H:%M:%S")) # 25/10/01 11:59:16
print(today.strftime("%Y/%m/%d %H:%M:%S %a %A %p"))
# 2025/10/01 11:59:16 Wed Wednesday AM
함수
# 사용자 정의 함수
# 함수, function, method
# test -> 변수
# test() -> 함수
# 함수 선언 형식 : def 함수이름():
data = [1, 4, 5, 7, 2]
print(data)
k = sorted(data) # 내장함수
print(k) # [1, 2, 4, 5, 7]
"""
함수의 정의
-> 자주 사용하는 명령어들을 그룹화하여 코드를 재사용하는 기법
-> 함수를 정의하는 것 만으로는 아무런 동작도 하지 않는다
-> 1) 매개변수(parameter)가 없는 경우
-> 2) 매개변수가 있는 경우
-> 3) 리턴(return)값이 있는 경우
-> 전달값(argument value)
"""
# 1) 매개변수가 없는 경우
def say_hello():
print("Hello Python")
print("안녕 파이썬")
# 함수 호출 -> 정의한 함수는 호출되어야만 실행된다
say_hello()
"""
Hello Python
안녕 파이썬
"""
# 2) 매개변수가 있는 경우
# 매개변수를 갖는 함수 정의
# -> 함수가 실행되는데 필요한 조건값
# -> 필요한 조건값을 함수이름 옆의 괄호 안에 명시
def test1(x): # x는 매개변수
# print(x)
y = x + 1
style = "test1({0}) => {0} + 1 = {1}"
print(style.format(x, y))
test1(3) # 3 -> 전달값(argument value)
test1(5)
test1(7)
## 매개변수가 2개 이상인 경우
## -> 여러개의 파라미터를 갖는 함수 정의
## -> 파라미터는 필요한 만큼 콤마로 구분하여 정의할 수 있다
## -> 다른 함수의 이름이 중복되지 않도록 주의
def test2(x, y):
z = x + y
style = "test2({0}) => {0} + {1} = {2}"
print(style.format(x, y, z))
test2(1, 3)
test2(2, 4)
test2(5, 6)
## 매개변수에 초기값 설정하기
# def test4(x, y = 0, z): # 에러 뒤에서부터 설정 가능함
def test3(x, y, z=0):
style = "test3({0} + {1} + {2}) => {0} + {1} + {2} = {3}"
print(style.format(x, y, z, x + y + z))
test3(2, 4, 6) # test3(2 + 4 + 6) => 2 + 4 + 6 = 12
test3(7, 8) # test3(7 + 8 + 0) => 7 + 8 + 0 = 15
test3(z=30, y=20, x=10) # test3(10 + 20 + 30) => 10 + 20 + 30 = 60
test3(y=100, x=300) # test3(300 + 100 + 0) => 300 + 100 + 0 = 400
# 3) 리턴값 있는 경우
# -> 형식) return
def plus(x, y):
z = x + y
return z
res = plus(1, 3)
print(res) # 4
res = plus(2, 4)
print(res) # 6
# 값, value -> 상수값, 변수값, 함수의 리턴값
# 리턴값을 갖는 함수는 그 결과를 직접 출력하거나 다른 연산에 활용할 수 있다
print(4) # 4
b = 6
print(b) # 6
print(plus(5, 6)) # 11
print(abs(-3) + plus(10, 20)) # 33
# return 문을 중간에 만나는 경우 그 즉시 호출시점으로 되돌아 간다
def test4(x, y):
if x < 10 or y < 10:
return 0
z = x + y
return z
print(test4(100, 200)) # 300
print(test4(5, 15)) # 0
#################################################################
# 문제1) ★기호 100번 출력하기
def graph(c, n):
print(c * n)
graph("★", 100)
# 문제2) 해당 년도가 윤년 확인하는 함수
def leap(year):
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
if leap(2025):
print("윤년")
else:
print("평년")
# 문제3) 팩토리얼값 구하기 4*3*2*1
def fact(num):
if num == 0:
return 1
else:
return num * fact(num - 1)
res = fact(4)
print(res)
# 문제4) 두 수사이의 차이를 구하는 함수 (절대값)
def diff(a, b):
return abs(a - b)
res = diff(7, -4)
print(res)
# 1. Scope 유효범위
"""
지역(local)변수와 전역(global)변수
- 함수 안에서 선언되는 변수와 밖에서 선언되는 변수의 범위
"""
def test5():
c = 1 + 3
print(c) # 4
# print(c) # NameError: name 'c' is not defined
test5()
def test6():
a = 1
print(a) # 1
# print(b) # NameError: name 'b' is not defined
test6()
def test7():
a = 3
b = 5
print(a) # 3
test7()
##################################################################
# 2. 전역변수
x = 100
def exam1():
print("exam1() : %d" % x) # 100
def exam2():
x = 200
print("exam2() : %d" % x) # 200 지역 변수의 우선순위가 더 높다
def exam3():
# 함수나 클래스 안에서 global로 선언하면
# 밖에서 선언된 변수를 함수나 클래스 안에서 가공이 가능한 형태로 바뀐다
global x
x = 300
print("exam3() : %d" % x)
print(x) # 100
exam1() # 100
exam2() # 200
exam3() # 300
print(x) # 300
exam1() # 300
exam2() # 200
##################################################################
# 3. 재귀함수
# -> 자신의 함수를 호출
def fact(f):
if f == 0:
return 1
else:
return f * fact(f - 1)
print(fact(3)) # 6
##################################################################
# 4. callback 함수
# -> 함수를 args 파라미터로 설정해서 사용
# -> 함수가 다른 함수를 호출하여 결과값을 실행
# -> 재귀함수에서 잘 사용
def hap(a, b):
return a + b
def gop(a, b):
return a * b
def calc(fn, a, b):
return fn(a, b)
print(calc(hap, 3, 5)) # 8
print(calc(gop, 4, 6)) # 24
##################################################################
# 5. lambda 함수
# -> 파라미터를 간단한 계산으로 리턴
# -> 메모리를 적게 사용하고 소멸한다
# -> 형식) lambda 파라미터 : 출력할 연산(return 값)
print(hap(2, 4)) # 6
sum = lambda a, b: a + b
print(sum(3, 5)) # 8
Numpy
# numpy 모듈
# -> 리스트의 기능 강화판. 과학 계산을 위한 라이브러리.
# -> 다차원 배열을 처리하는데 필요한 여러 기능을 제공하고 있다.
# 배열 Array : 데이터를 모아놓은 자료구조
# -> 리스트, 튜플, 딕셔너리 등
"""
설치 모듈 확인
>pip list
numpy 모듈 설치
>pip install numpy
numpy 모듈 삭제
>pip uninstall -y numpy
"""
import numpy as np
arr = [1, 2, 3]
print(arr) # [1, 2, 3]
print(len(arr)) # 3
# 리스트 값을 1차원 배열 만들기
a = np.array(arr)
print(a) # [1 2 3]
print(len(a)) # 3
print(type(a)) # <class 'numpy.ndarray'>
# 실수가 범위가 더 크므로 모든 요소가 실수형으로 변환
b = np.array([1, 2.3, 4, 5.6])
print(b) # [1. 2.3 4. 5.6]
# 모든 타입이 문자열로 변환
c = np.array([1.2, 3, "4"])
print(c) # ['1.2' '3' '4']
d = np.array([1, 2.3, 4, 5.6], dtype="int")
print(d) # [1 2 4 5]
e = np.array([1, 2.3, 4, 5.6], dtype="float")
print(e) # [1. 2.3 4. 5.6]
# enumerate() : 반복문에서 인덱스(index)와 값(value)을 동시에 가져올 때
for idx, v in enumerate(e):
print(f"{idx}번째 요소 : {v}")
"""
0번째 요소 : 1.0
1번째 요소 : 2.3
2번째 요소 : 4.0
3번째 요소 : 5.6
"""'Courses > 아이티윌 오라클 DBA 과정' 카테고리의 다른 글
| 251010 TIL (0) | 2025.10.10 |
|---|---|
| 251002 TIL (0) | 2025.10.02 |
| 250930 TIL (0) | 2025.09.30 |
| 250929 TIL (0) | 2025.09.29 |
| 250926 TIL (0) | 2025.09.26 |