데이터분석

[23.06.08] Python comprehension, random - 05(2)

gmwoo 2023. 6. 8. 17:50

1. comprehension (컴프리헨션)

 - list 타입에만 축약
 - list 타입에서 데이터 추출하기 위한 용도

[변수명 for 변수명 리스트타입]
[변수명 for 변수명 리스트타입 if 조건식]  # 조건식이 True인 것만 추출
[함수(변수명) for 변수명 리스트타입 if 조건식]  # 조건식이 True인 것중에 값 변경해서 추출

 1) soft copy(shallow copy)와 hard copy(deep copy)
 - 파이썬의 모든 변수는 데이터 자체가 아니라 데이터의 주소를 저장
 - EX) 만약 nums 라는 변수가 있을 때, nums2 = nums 라고 하면, 이 때 nums2에는 nums에 저장된 주소값이 복사되어 실제 데이터는 하나이고 두 개의 변수가 같은 데이터를 소유하게 됨
   => soft copy   :   모든 참조형 또는 포인터형 변수의 기본 특징
예제 1) 리스트 형태로 copy

wordList = ["school", "book", "bookstore", "desk", "hospital", "survey",
            "assembly", "president", "python", "flower", "sky", "cloud",
            "language", "phone", "house"]
nums = [1,2,33,4,6,23,26,17,19,8,19,27]

##### soft copy
nums2 = nums  # 이 때 두 변수는 같은 데이터 공간을 소유
nums2[0] = 100
print(nums2)
print(nums)

##### hard copy
nums2 = [x for x in nums] 
nums[0] = 100

print(nums)
print(nums2)

evenList = [n for n in nums if n%2==0]
print(evenList)

# 3의 배수만 추출
multiple_3 = [i for i in nums if i%3==0]  # 컴프리헨션
print("comprehension", multiple_3)
print("lambda,filter", list(filter(lambda i: i%3==0, nums)))

# wordList에서 문자열 크기가 5글자 넘어가는 것만 추출
wordListOut = [x for x in wordList if len(x)>5]
print(wordListOut)

# wordList에서 문자열 크기가 5글자 넘어가면서 대문자로 추출
wordListOut_upper = [x.upper() for x in wordList if len(x)>5]
print(wordListOut_upper)

 
예제 2) dict 타입에서 copy

# 나이가 30세 넘어가는 사람 추출
dataList = [
    {"name": "강감찬", "age": 23},
    {"name": "감강찬", "age": 20},
    {"name": "김연경", "age": 33},
    {"name": "조승연", "age": 28},
    {"name": "김연아", "age": 30},
    {"name": "이순신", "age": 43},
    {"name": "서희", "age": 35},
    {"name": "윤관", "age": 27},
    {"name": "박세리", "age": 43},
]
age30 = [i for i in dataList if i["age"]>=30]
print(age30)

 
 - 파이썬의 장점으로, 벡터 연산이므로 타입 전환이 자유로움
 - list는 벡터연산 지원이 되지 않으므로, numpy 모듈을 불러와 벡터 연산

import numpy as np

x = [1,2,3,4,5]  # list 타입
print(x)
x = np.array(x)  # ndarray 타입으로 전환
print(x)
y = 2*x + 1   # 벡터 연산
print(y, type(y))

 
문제 1) 성적처리 - 총점, 평균, 학점 출력 후, 해당 인물 검색, 수정, 삭제, 정렬 함수 만들기

scoreList = [
    {"name":"홍길동", "kor":90, "eng":80, "mat":90},
    {"name":"둘리", "kor":100, "eng":40, "mat":90},
    {"name":"임꺽정", "kor":100, "eng":100, "mat":100},
    {"name":"장길산", "kor":70, "eng":60, "mat":70},
    {"name":"도우너", "kor":90, "eng":80, "mat":90},
]

# 총점, 평균, 학점

def process(score):
    score["total"] = score["kor"] + score["eng"] + score["mat"]
    score["avg"] = round(score["total"] / 3, 2)
    score["grade"] = ""
    if score["avg"] >= 90:
        score["grade"] = '수'
    elif score["avg"] >=80:
        score["grade"] = '우'
    elif score["avg"] >=70:
        score["grade"] = '미'
    elif score["avg"] >=60:
        score["grade"] = '양'
    else:
        score["grade"] = '가'

def outp(s):
    print(f"{s['name']} {s['kor']}", end=' ')
    print(f"{s['eng']} {s['mat']}", end=' ')
    print(f"{s['total']} {s['avg']} {s['grade']}")

def processAll():
    for score in scoreList:
        process(score)
        
def outpAll():
    for score in scoreList:
        outp(score)

processAll()
outpAll()

# 검색 함수
def search():
    name = input("찾을 이름: ")
    # result = list(filter(lambda x: x['name']==name, scoreList))   # lambda, filter 사용
    result = [i for i in scoreList if i["name"]==name]   # comprehension 사용
    if len(result) == 0:
        print(f"{name}을 찾을 수 없음")
        return
    
    for item in result:
        outp(item)
    
# 수정 함수
def modify():
    name = input("수정할 이름: ")
    # result = list(filter(lambda x: x['name']==name, scoreList))   # lambda, filter 사용
    result = [i for i in scoreList if i["name"]==name]   # comprehension 사용
    if len(result) == 0:
        print(f"{name}을 찾을 수 없음")
        return
    
    result[0]['name'] = input("바꿀 이름은: ")
    result[0]['kor'] = int(input("국어 점수: "))
    result[0]['eng'] = int(input("영어 점수: "))
    result[0]['mat'] = int(input("수학 점수: "))
    process(result[0])   # 다시 계산
    outpAll()
    
# 삭제 함수
def delete():
    name = input("삭제할 이름: ")
    # result = list(filter(lambda x: x['name']==name, scoreList))   # lambda, filter 사용
    result = [i for i in scoreList if i["name"]==name]   # comprehension 사용
    if len(result) == 0:
        print(f"{name}을 찾을 수 없음")
        return
    
    scoreList.remove(result[0])
    outpAll()
    
# 정렬 함수
#  이름으로. 총점으로. 국어 성적으로 정렬 
            
def sorting():
    sel = int(input("이름 순: 1, 총점 순: 2, 국어 성적 순: 3 고르시오 -> "))
    if sel == 1:
        key = "name"
        
    elif sel == 2:
        key = "total"
        
    elif sel == 3:
        key = "kor"
    
    sortedList = sorted(scoreList, key=lambda score: score[key])
    for s in sortedList:
        outp(s)   
        
def appending():
    score = dict()
    score["name"]=input('이름: ')
    score["kor"]=int(input('국어: '))
    score["eng"]=int(input('영어: '))
    score["mat"]=int(input('수학: '))
    process(score)
    scoreList.append(score)

def close():
    return

def menu():  # 고르시오
    menus = ['1.추가', "2.출력", "3.검색", "4.수정", "5.삭제", "6.정렬", "0.종료"]
    # process()
    
    for menu in menus:
        print(menu)
        
def start():
    functionList = [None, appending, outpAll, search, modify, 
                    delete, sorting]
    processAll()
    while True:
        menu()
        sel = int(input("선택: "))
        
        if sel<1 or sel>len(functionList):
            print('종료')
            return
        
        functionList[sel]()   #### 함수 호출
        
start()

 

2. random

 - import random 
 - 외부라이브러리를 불러온다 자바의 import 는 라이브러리 이름이 길어서 이름을 생략
 - 파이썬의 import는 라이브러리를 메모리로 불러와서 결합한다
 - print( random.randint(1,3)) #1~3에 해당하는 랜덤값을 생성한다. 컴퓨터내부의 시계를 이용한다
 - 리눅스: 1993년에 리누스 토발즈라는 대학생이 os를 만들면서 unix(서버용) => linux(PC용)
                 다른사람들도 공부해라 소스공개를 함
 - 이전부터 소스공개를 주장하던 협회분들이 같이 하자 GNU 협약
 - 오픈소스: 파이썬 번역기 프로그램 소스를 공개한다
 - 오픈소스가 무료인 경우가 많은거지 무료여야 하는건 아니다.
 - 하드웨어 : OS : 번역을 할대 OS에 특화
 - 하드웨어 : OS : 자바가상머신 : 번역 자바가상머신이 알아듣게 싱행할때 다시 OS가 알아듣는 말로
 - GNU 협약을 따르는 경우 무조건 소스 공개를 해야 한다
 - oracle, mysql, mysql(무료)
문제 2) 가위바위보

import random 

gameList=[]

#컴퓨터승 1, 사람승 2 무승부 3
def gameStart():
    #1.컴퓨터가 값을 갖고 있다 
    computer = random.randint(1,3)
    print("컴퓨터 : ", computer)
    person = int(input("1.가위 2.바위 3.보"))
    winner = whoWin(computer, person)
    gameInfo={"computer":computer, "person":person, "winner":winner}
    output(gameInfo)
    gameList.append(gameInfo)
    
def output(gameInfo):
    temp1 = ["", "가위", "바위", "보"]
    temp2 = ["", "컴퓨터승", "사람승", "무승부"]
    c = gameInfo['computer']
    p = gameInfo['person']
    w = gameInfo['winner']
    print(f"컴퓨터 : {temp1[c]} 사람:{temp1[p]} 승부:{temp2[w]}") 
        
def whoWin(computer, person):
    if computer== person:
        return 3
    
    if computer == 1:
        if person==2:
            return 2 #사람승
        else:
            return 1 
    
    if computer == 2:
        if person==1:
            return 1 #
        else:
            return 2       
    
    if computer == 3:
        if person==1:
            return 2 #
        else:
            return 1  
    

gameStart()
반응형