본문 바로가기

Python

자주 이용되는 파이썬 모듈

728x90

1. copy 모듈 : 객체를 복사할 때 사용하는 모듈

 

shallow copy : 객체의 참조값(주소)만 복사되고 객체는 공유된다. 원본 객체에 영향을 끼치므로 완벽한 복사가 아니다.

 

deep copy : 독립된 객체를 복사해준다. 원본 객체에 영향을 미치지 않는다.

 

import copy
colors = ["red", 'blue', 'green']

# shallow copy 얇은 복사
shallow_clone = colors

# deep copy 깊은 복사
clone = copy.deepcopy(colors)

colors[0]="바뀜"
shallow_clone[2]= "안녕"

clone[0]="빨강"

print(colors)
print(shallow_clone)
print(clone)

#['바뀜', 'blue', '안녕']
#['바뀜', 'blue', '안녕']
#['빨강', 'blue', 'green']

 

 

2. random 모듈 : 난수를 발생시킬 때 사용하는 모듈

 

randint, random, randrange, choice, shuffle

 

import random

# 1 이상 ~ 6 이하 사이의 값을 랜덤하게 출력해준다.
print("주사위의 눈: ", random.randint(1,6))

# random() : 0.0 이상 ~ 1.0 미만의 난수를 발생
print("random() : ", random.random())

# 0.0 이상 ~ 100 미만의 난수 발생
print("random() : ", random.random() * 100)

# randrange(start, stop, [,step])
# start 이상 stop 미만의 정수 중 난수 발생
print("randrange() : ", random.randrange(0,100,3))

# choice() : 주어진 iterable의 항목을 랜덤하게 발생시킨다.
list1 = ['tom', 'apple', 'orange', 'bannana']
print(random.choice(list1))

# shuffle() : 리스트의 항목을 랜덤하게 섞어주는 함수
list2 = [x for x in range(10)]
print('섞기 전 : ', list2)
random.shuffle(list2)
print('섞은 후 : ', list2)

 

 

3. time 모듈

 

import time

# 1970년 1월 1일 자정이후 지금까지 흐른 절대시간을 초단위로 출력
# 프로그램 성능테스트
previous = time.time()

# 프로그램을 1초간 일시정지
time.sleep(1)
later = time.time()
print(later - previous)

# asctime() 는 현재 날짜와 시간을 문자열 형태로 표시한다.
print("현재 날짜 및 시간 : ", time.asctime())

 

 

4. calendar 모듈

 

import calendar

# 2024.2 월 달력 출력하기
cal = calendar.month(2024,2)
print(cal)

 

 

5. sys 모듈

 

import sys

# sys 모듈은 시스템에 관련된 내용을 파이썬 인터프리터에게 다양한 정보를 제공하는 모듈
print("파이썬 설치경로 : ", sys.prefix)
print("파이썬 버전 : ", sys.version)

'Python' 카테고리의 다른 글

데이터 베이스  (0) 2024.02.19
(Python) 예외 처리  (0) 2024.01.29
(Python) Iterable 과 Sequence  (0) 2024.01.24