-> 리스트 컴프리헨션으로 대체 가능
# 리스트 컴프리헨션
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]
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})
persons = ['김철수' ,'김영희' ,'김민수']
fruits = ['사과', '오렌지', '멜론']
items = []
for i, person in enumerate(zip(persons, fruits)):
items.append((i,person))
print(items)
# [(0, ('김철수', '사과')), (1, ('김영희', '오렌지')), (2, ('김민수', '멜론'))]
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]
print(min(nums)) # 1
print(max(nums)) # 10
alpha = ['e', 'j', 'z', 'o', 'p', 'q']
print(min(alpha)) # e
print(max(alpha)) # z
다른 플랫폼 간의 소통을 위한 표준 데이터 형식
자바스크립트의 객체를 정의하는 형식을 빌려온 것 ( 그냥 문자열 임 )
{ '이름' : '값', '이름' : '값' }
메서드
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))
# 파일 출력
file = open('test.txt', 'w', encoding='UTF-8')
file.write('안녕하세요.')
file.write('반갑습니다.')
file.close()
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()
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)
# 파일 쓰기
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)
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))
# 동기식 함수 [ 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)