26.8.20 / Thu

BaO·2026년 8월 20일

TIL

목록 보기
6/33

내장 함수

map() & filter()

  • map() : 변환
  • filter() : 판별 -> 정제

-> 리스트 컴프리헨션으로 대체 가능

# 리스트 컴프리헨션
nums = [*range(1, 11)] # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

nums2 = [x ** 2 for x in nums] # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

nums3 = [x for x in nums if x % 2 == 1] # [1, 3, 5, 7, 9]

enumerate()

  • 리스트나 배열의 요소를 (인덱스, 값) 튜플 형태로 반환
fruits = ['사과', '오렌지', '멜론', '망고']

# num = 1
# for fruit in fruits :
#     print(f'{num}. {fruit}')
#     num += 1

for idx, value in enumerate(fruits): # (index, value)
    print(f'{idx}. {value})

zip()

  • 다수의 리스트, 튜플을 각 인덱스 순서대로 매칭해서 반환
    • itertools 모듈 zip_longest : 각 리스트의 요소의 개수가 다를때 남은 요소를 매칭하기 위해서 사용
persons = ['김철수' ,'김영희' ,'김민수']
fruits = ['사과', '오렌지', '멜론']

items = []
for i, person in enumerate(zip(persons, fruits)):
    items.append((i,person))

print(items)
# [(0, ('김철수', '사과')), (1, ('김영희', '오렌지')), (2, ('김민수', '멜론'))]

sorted()

  • 리스트.sort() : 원본 데이터 정렬
  • sorted(Iterable) : 원본 데이터 유지, 복사한 객체를 생성해서 정렬 ( 불변객체 )
import random
nums = [*range(1, 11)]
random.shuffle(nums)

print(nums)  # [8, 9, 4, 1, 3, 7, 10, 5, 6, 2]
nums.sort()  # 원본 데이터를 정렬
print(nums)  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

random.shuffle(nums)
print(nums)  # [2, 10, 4, 3, 8, 9, 1, 6, 5, 7]
nums2 = sorted(nums) # 원본 데이터 유지 후, 복사본 값 정렬 후 리스트로 반환
print(nums2) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums)  # [2, 10, 4, 3, 8, 9, 1, 6, 5, 7]

min(), max()

  • min() : 최소값 / 오름차순 정렬 후 가장 처음 요소
  • max() : 최대값 / 오름차순 정렬 후 가장 마지막 요소
print(min(nums)) # 1
print(max(nums)) # 10

alpha = ['e', 'j', 'z', 'o', 'p', 'q']
print(min(alpha)) # e
print(max(alpha)) # z

표준 라이브러리

1. datetime & time

  • datetime : 모듈명
    • 날짜와 시간 : datetime
    • 날짜 : date
    • 시간 : time
    • 차이 : timedelta

JSON

  • 다른 플랫폼 간의 소통을 위한 표준 데이터 형식

  • 자바스크립트의 객체를 정의하는 형식을 빌려온 것 ( 그냥 문자열 임 )

  • { '이름' : '값', '이름' : '값' }

  • 메서드

    • json.dumps(obj) : 파이썬 객체(딕셔너리, 리스트)를 JSON 형식 문자열로 변환
    • json.loads(s) : JSON 형식의 문자열을 파이썬 객체로 변환
    • json.dump(obj, fp) : 파이썬 객체의 파일을 JSON 형식의 파일로 직접 저장
    • json.load(fp) : JSON 형식의 파일을 파이썬 객체로 변환
import json

# 파이썬 객체 -> JSON 문자열
user = {
    'name' : '김철수',
    'age' : 20
}

json_string = json.dumps(user)
print('json string : ', json_string, 'type : ', type(json_string))
# json string :  {"name": "\uae40\ucca0\uc218", "age": 20} type :  <class 'str'>
json_string = json.dumps(user, ensure_ascii=False)
print('json string : ', json_string, 'type : ', type(json_string))
# json string :  {"name": "김철수", "age": 20} type :  <class 'str'>
# JSON 문자열 -> 파이썬 객체
nums_string = "[1,2,3,4,5]"
user_string = '{"name": "김철수", "age": 20}'

nums = json.loads(nums_string)
usrs = json.loads(user_string)

print(nums, type(nums))
print(usrs, type(usrs))

파일 입출력 & 구조화된 데이터 변환

파일 입출력

  • 입력 ( Input ) : 파일에 있는 데이터 읽기
    • read(..)
  • 출력 ( Output ) : 데이터를 파일로 작성
    • write(..)
# 파일 출력
file = open('test.txt', 'w', encoding='UTF-8')

file.write('안녕하세요.')
file.write('반갑습니다.')

file.close()

with open()의 자원 자동 해제

  • with 구문 : 첫 라인에서 __enter__(..) 실행, 마지막 라인 실행 후 __exit__(..) 실행
class MyResource :
    def __enter__(self):
        print('__enter__ 호출')
        return self

    # with 구문 종료되었을때 또는 예외가 발생했을때 호출
    # 예외 발생시 exc_type -> 예외 클래스 종류
    #           exc_val -> 예외 메세지
    #           exc_tb -> TraceBack 메세지
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('__exit__ 호출')
# 파일에서 작성하는 위치(파일 포인터)가 가장 앞으로 이용해서 내용 대체
with open("test.txt", "w", encoding="UTF-8") as fp:
    fp.write('Hello')

# 파일 포인터를 이동하지 않고 누적해서 작성
with open('test.txt', 'a', encoding='UTF-8') as fp :
    fp.write('안녕하세요.\n')

텍스트 파일 읽기 함수 read, readline, readlines

  • read : 한번에 전체 텍스트 읽어오기
  • readline : 한 라인 읽어오기
  • readlines : 라인별로 읽어서 리스트로 반환
# read()
with open('test.txt', 'r', encoding='UTF-8') as fp:
    text = fp.read()
    print(text)
# readline()
with open('test.txt', 'r', encoding='UTF-8') as fp:

    # text = fp.readline()
    # text2 = fp.readline()
    # print(text, text2)

    # :=  -> 값이 있다 = True, 값이 없다 = False
    while(text := fp.readline()): # 한 줄씩 읽어서 메모리에 적재함으로 메모리 소비가 적음
        print(text)
# readlines()
# 한꺼번에 메모리에 올리기 때문에 메모리 소비가 많음
# 적은 용량에 적합함
with open('test.txt', 'r', encoding='UTF-8') as fp:
    lines = fp.readlines()
    print(lines)
# readline()과 동일한 효과
with open('test.txt', 'r', encoding='UTF-8') as fp:
    for line in fp:
        print(line)

CSV 형식

  • CSV : Comma Seperated Value
    • writer(파일 포인터) : 쓰기
      • writerow(iterable)
    • reader(파일 포인터) : 읽기
# 파일 쓰기
import csv

with open('member.csv', 'w', encoding='UTF-8', newline='') as fp :
    writer = csv.writer(fp)
    writer.writerow(['이름', '나이', '전화번호'])
    writer.writerow(['김철수', 20, '010-1000-1000'])
# 파일 읽기
with open('member.csv', 'r', encoding='UTF-8') as fp :
    reader = csv.reader(fp)
    members = list(reader) # 리스트로 변경해야 value 확인 가능
    print(members)

JSON 형식

  • 파이썬 객체 -> 전송 가능한 JSON 형식으로 변환 - 직렬화(Serialize)
  • JSON 문자열(전송 받은 문자열) -> 파이썬 객체로 변환 - 역직렬화
import json

# dict -> json 파일로 저장 ( 직렬화 )
user = {
    'name' : '김영희',
    'age' : 20,
    'mobile' : '010-1000-1000'
}

with open('user.json', 'w', encoding='UTF-8') as fp:
    json.dump(user, fp, indent=4, ensure_ascii=False)
# json -> dict
with open('user.json', 'r', encoding='UTF-8') as fp:
    user2 = json.load(fp)
    print(user2)
    print(type(user2))

동기(Sync) & 비동기(Async)

# 동기식 함수 [ SubRoutine ]
import time

def work(title, seconds):
    time.sleep(seconds)
    print(title, '완료')

start = time.perf_counter() # 작업 시작 시간

work('a작업', 2)
work('b작업', 3)
work('c작업', 1)


end = time.perf_counter() # 작업 종료 시간
print('걸린 시간 : ', end - start)
# 비동기식 함수 [ CoRoutine ]
import asyncio
import time

async def async_work(title, seconds):
    asyncio.sleep(seconds)
    print(title, '완료')

async def main():
    asyncio.gather(
        async_work('A작업', 2),
        async_work('B작업', 3),
        async_work('C작업', 1)
    )


start = time.perf_counter()
await main()
end = time.perf_counter()
print('걸린 시간 : ', end - start)

0개의 댓글