Networks/Python

SK networks AI Camp - Python 표준 라이브러리(함수)

코딩하는 Español되기 2024. 7. 16. 08:30

모듈(module), 패키지(Package)

○ 모듈 : 변수, 함수, 클래스를 모아놓은. py 확장자 파일

    ● .py 파일 : 마크다운이나 셀같은 정보는 없고 순수한 파이썬 코드만 존재

    ● .ipynb 파일 : 파이썬 언어, 데이터로 작업하고 실행할 수 있도록 도와주는 Interactive 한 개발 환경에서 실행되는 파일

○ 패키지 : 모듈의 기능을 폴더별로 정리한 개념

    ● 패키지 생성 : 기능별로 폴더를 정리하는 것과 비슷한 개념

 # 패키지에서 모듈 불러오기
from <패키지명> import <모듈명>
# 모듈안에 함수와 클래스 불러오기
from <모듈명> import <함수 or 클래스>
# 별칭 정해주기
import <모듈명> as <별칭>

표준 라이브러리(함수)

○ 파이썬 표준 라이브러리는 파이썬을 설치할 때 자동으로 설치됨

표준 라이브러리에서 주요 함수들

Collections

: 시퀀스 자료형 데이터의 값의 개수를 딕셔너리 형태로 반환

○ Counter

from collections import Counter
lst = ['aa', 'aa','aa', 'bb', 'bb', 'ee', 'tt']
counter = Counter(lst)
counter

print(dict(counter))
print(list(counter.elements()))

    ● most_common(k) : k 숫자만큼 큰 인자를 리턴해줌

print(counter.most_common(1)) # 1번째로 많은 것까지 출력
print(counter.most_common(2)) # 2번째로 많은 것까지 출력

    ● 산술 연산자 활용

counter1 = Counter(['A', 'A', 'B'])
counter2 = Counter(['A', 'B', 'B'])
print(f'counter1 : {counter1}')
print(f'counter2 : {counter2}')

counter1 + counter2, counter1 - counter2

○ OrderedDict

: 순서를 가진 딕셔너리 객체, key/value 생성한 순서대로 저장

from collections import OrderedDict
lst = [('a', 11), ('b', 22), ('c', 33)]
ordere_dict = OrderedDict(lst)
ordere_dict # lst의 데이터 순서대로 저장

    ● 마지막 순서 pop(추출) / last = False 시 첫 번째 순서 pop(추출)

ordere_dict.popitem(last=False)
ordere_dict

    ● 마지막으로 key:value 옮기기 / last = False 시 첫 번째로

ordere_dict.move_to_end(key='b', last = True)
ordere_dict

○ defaultdict

: 딕셔너리의 단점으로 없는 key 접근 시 에러가 발생하는 단점을 보완

  딕셔너리에 없는 key에 접근 시 지정한 기본값을 이용해 key, value를 생성

from collections import defaultdict

word = "Hello world"
tup_list = [
    ('경제', '10시 경제기사'),
    ('정치', '10시 정치기사'),
    ('사회', '10시 사회기사'),
    ('경제', '14시 경제기사'),
    ('정치', '15시 정치기사')
]

    ● 일반적인 사전 기본값 처리

def countLetters(word):
    counter={}
    for letter in word:
        if letter not in counter:
            counter[letter] = 0
        counter[letter] += 1
    return counter

countLetters(word)

def countLetters(word):
    counter={}
    for letter in word:
        counter.setdefault(letter, 0)
        counter[letter] += 1
    return counter

countLetters(word)

news_dict = {}
for k, v in tup_list:
    if news_dict.get(k) is None:
        news_dict[k] = []
    news_dict[k].append(v)
news_dict

    ● defaultdict 사용

def countLetters(word):
    counter= defaultdict(int)
    for letter in word:
        counter[letter] += 1
    return counter

countLetters(word)

news_dict = defaultdict(list)

for k, v in tup_list:
    news_dict[k].append(v)

news_dict

math

import math
math.pi
math.e
math.exp(10) # e**10
math.log(10)
math.sqrt(100)
math.pow(2, 4) # 2 ** 4
math.ceil(4.55), math.floor(4.55)

random

: 난수를 발생시키는 모듈

import random

random.random() # 0.0  1.0 사이 실수값 랜덤 추출
random.randint(1, 10) # 1 ~ 10 사이의 정수 랜덤 추출
random.choice([2,4,6,8]) # 입력 받은 리스트 중에서 한개만 랜덤 추출
random.sample([1,2,3,4,5], 2) # 첫번째 입력 리스트에서 두번째 입력 갯수만큼 랜덤 추출

datetime

    ● 오늘 날짜와 시간

import datetime

datetime.datetime.now()

    ● 날짜 차이

date1 = datetime.date(2023, 3, 14)
date2 = datetime.date(2022, 3, 14)
diff = date1 - date2
diff.days

    ● 요일 확인

day1 = datetime.date(2023, 3, 14)
day1.weekday() # 1 : 화요일, 2 : 수요일 .....

time

    ● time.time()

       : UTC(협정 세계 표준시)를 사용해 현재 시간을 실수 형태로 리턴하는 함수

         1970년 1월 1일 0시 0분 0초를 기준으로 지난 시간을 초단위로 돌려줌

import time
time.time()

    ● time.sleep

       : 주로 루프 안에서 많이 사용. 이 함수를 사용하면 일정 시간 간격을 두고 루프를 실행 가능

for i in range(5):
    print(i)
    time.sleep(1) # 1초 간격으로 for문 실행

json

: JSON 데이터를 쉽게 처리하고자 사용하는 모듈

dic = {
    'name' : '홍길동',
    'birth' : '1212',
    'age' : 33
}

print(f'{type(dic)}/ {dic}')

import json

json_str = json.dumps(dic) # dic to json 문자열
json_str

json.loads(json_str) # json 문자열 to dic