리스트와 비슷하지만 아이템 변경이 불가하다
'()'를 이용해서 선언하고, 데이터 구분은 ','를 이용한다
튜플도 리스트와 마찬가지로 아이템에 자동으로 부여되는 번호표가 있다
튜플 아이템은 인덱스를 이용해서 조회 가능하다
studentsTuple = ('홍길동', '박찬호', '이용규', '박승철', '김지은')
searchName = input('학생 이름 입력: ') if searchName in studentsTuple: print('{} 학생은 우리반 학생입니다.'.format(searchName)) else: print('{} 학생은 우리반 학생이 아닙니다.'.format(searchName))
in, not in 키워드는 문자열에서도 사용 가능하다
(실습) 컴퓨터가 1부터 10까지 5개의 난수를 생성한 후, 사용자가 입력한 숫자가 있는지 또는 없는지를 출력하는 프로그램
import random
randomNumbers = random.sample(range(1, 11), 5) userNumber = int(input('숫자 입력(확률 50%): '))
if userNumber in randomNumbers: print('빙고!') else: print('다음 기회에~')
print('randomNumbers: {}'.format(randomNumbers)) print('userNumber: {}'.format(userNumber))
wrongWord = ['쩔었다', '짭새', '꼽사리', '먹튀', '지린', '쪼개다', '뒷담 까다'] sentence = '짭새 등장에 강도들은 모두 쩔었다. 그리고 강도 들은 지린 듯 도망갔다.'
for word in wrongWord: if word in sentence: print('비속어: {}'.format(word))
리스트와 마찬가지로, 튜플에 저장된 아이템 개수를 튜플 길이라고 한다
len() 반복문을 이용하면 튜플의 아이템 조회가 가능하다
for문
for i in range(len(students)): print('i : {}'.format(i)) print('students[{}] : {}'.format(i, students[i]))
while문
n = 0 sLength = len(students) while n < sLength: print('n : {}'.format(n)) print('students[{}] : {}'.format(n, students[n])) n += 1
iterable
for student in students: print('student : {}'.format(student))
myFavoriteSports = ('수영', '배구', '야구', '조깅')
for문
for i in range(len(myFavoriteSports)): print('myFavoriteSports[{}]: {}'.format(i, myFavoriteSports[i]))
while문
n = 0 while n < len(myFavoriteSports): print('myFavoriteSports[{}]: {}'.format(n, myFavoriteSports[n])) n += 1
두 개의 튜플을 결합할 수 있다
(A 튜플 + B 튜플 = C 튜플)
리스트에서 사용할 수 있는 extend() 함수를 튜플에서는 사용할 수 없다
(실습) 튜플을 이용해서 나와 친구가 좋아하는 번호를 합치되 번호가 중복되지 않게 하는 프로그램
myFavoriteNumbers = (1, 3, 5, 6, 7) friendFavoriteNumbers = (2, 3, 5, 8, 10)
print('myFavoriteNumbers: {}'.format(myFavoriteNumbers)) print('friendFavoriteNumbers: {}'.format(friendFavoriteNumbers))
(number, ) -> 튜플로 만들어줌
for number in friendFavoriteNumbers: if number not in myFavoriteNumbers: myFavoriteNumbers = myFavoriteNumbers + (number, )
print('myFavoriteNumbers: {}'.format(myFavoriteNumbers))
리스트와 마찬가지로 [n:m]을 이용하면 리스트에서 원하는 아이템만 뽑아낼 수 있다
슬라이싱 할 때 단계를 설정할 수 있다
numbers = (2, 50, 0.12, 1, 9, 7, 17, 35, 100, 3.14) print('numbers: {}'.format(numbers[2:-2])) print('numbers: {}'.format(numbers[2:-2:2])) print('numbers: {}'.format(numbers[:-2:2])) print('numbers: {}'.format(numbers[::2]))
튜플은 슬라이싱을 이용해서 아이템을 변경할 수 없다
slice() 함수를 이용해서 아이템을 슬라이싱할 수 있다
students = ('홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은') print('students: {}'.format(students))
print('students: {}'.format(students[slice(2, 4)]))
시작 값 생략
print('students: {}'.format(students[slice(4)]))
len() -> 끝까지
print('students: {}'.format(students[slice(2, len(students))]))
-2까지
print('students: {}'.format(students[slice(2, len(students)-2)]))
6-5 부터 6-2 까지 - > 1 부터 4 까지
print('students: {}'.format(students[slice(len(students)-5, len(students)-2)]))
튜플은 리스트와 달리 아이템 추가, 변경, 삭제가 불가하다
튜플은 선언 시 괄호 생략이 가능하다
리스트와 튜플은 자료형 변환이 가능하다
(실습) 튜플을 이용한 점수표에서 최저, 최고 점수를 삭제한 후 총점과 평균을 출력해 보자
playerScore = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0) print('playerScore: {}'.format(playerScore)) print(type(playerScore))
리스트로 변경후 값 변경
playerScore = list(playerScore) print(type(playerScore))
정렬, 최저 및 최고 점수 삭제
playerScore.sort() print('playerScore: {}'.format(playerScore)) playerScore.pop(0) playerScore.pop(len(playerScore) - 1)
다시 튜플로 변경
playerScore = tuple(playerScore) print('playerScore: {}'.format(playerScore)) print(type(playerScore))
총점
sum = 0 avg = 0 for score in playerScore: sum += score
평균
avg = sum / len(playerScore)
print('총점: %.2f' % sum) print('평점: %.2f' % avg)
튜플은 수정이 불가하기 때문에 리스트로 변환 후 정렬하자
sort() 함수를 이용하면 아이템을 정렬할 수 있다
sort() 함수를 이용하면 튜플도 정렬할 수 있다
sorted() 함수를 이용하면 정렬할 수 있다
students = ('홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은')
sortedStudents = sorted(students) print('sortedStudents type: {}'.format(type(sortedStudents))) print('sortedStudents: {}'.format(sortedStudents))
playerScore = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0) print('playerScore: {}'.format(playerScore))
리스트로 변경후 값 변경, 정렬
playerScore = list(playerScore) playerScore.sort() print('playerScore: {}'.format(playerScore))
최저 및 최고 점수 삭제
playerScore.pop(0) playerScore.pop(len(playerScore) - 1)
다시 튜플로 변경
playerScore = tuple(playerScore) print('playerScore: {}'.format(playerScore))
총점
sum = 0 avg = 0 for score in playerScore: sum += score
평균
avg = sum / len(playerScore)
print('총점: %.2f' % sum) print('평점: %.2f' % avg)
cars = '그랜저', '소나타', '말리부', '카니발', '쏘렌토'
for i in range(len(cars)): print(cars[i])
for car in cars: print(car)
studentCnts = (1, 19), (2, 20), (3, 22), (4, 18), (5, 21)
for classNo, cnt in studentCnts: print('{}학급 학생수: {}'.format(classNo, cnt))
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17) sum = 0 avg = 0 for classNo, cnt in studentCnts: print('{}학급 학생수: {}명'.format(classNo, cnt)) sum += cnt
print('전체 학생 수: {}명'.format(sum)) print('평균 학생 수: {}명'.format(sum / len(studentCnts)))
minScore = 60 scores = ( ('국어', 58), ('영어', 77), ('수학', 89), ('과학', 99), ('국사', 50))
item
for item in scores: if item[1] < minScore: print('과락 과목: {}, 점수: {}'.format(item[0], item[1]))
iterable
for subject, score in scores: if score < minScore: print('과락 과목: {}, 점수: {}'.format(subject, score))
continue
for subject, score in scores: if score >= minScore: continue print('과락 과목: {}, 점수: {}'.format(subject, score))
minScore = 60
korScore = int(input('국어 점수: ')) engScore = int(input('영어 점수: ')) matScore = int(input('수학 점수: ')) sciScore = int(input('과학 점수: ')) hisScore = int(input('국사 점수: '))
scores = ( ('국어', korScore), ('영어', engScore), ('수학', matScore), ('과학', sciScore), ('국사', hisScore))
item
for item in scores: if item[1] < minScore: print('과락 과목: {}, 점수: {}'.format(item[0], item[1]))
iterable
for subject, score in scores: if score < minScore: print('과락 과목: {}, 점수: {}'.format(subject, score))
continue
for subject, score in scores: if score >= minScore: continue print('과락 과목: {}, 점수: {}'.format(subject, score))
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)
minclassNo = 0 maxclassNo = 0 minCnt = 0 maxCnt = 0
for classNo, cnt in studentCnts: if minCnt == 0 or minCnt > cnt: minclassNo = classNo minCnt = cnt
if maxCnt < cnt: maxclassNo = classNo maxCnt = cnt
print('학생 수가 가장 적은 학급(학생수): {}학급({}명)'.format(minclassNo, minCnt)) print('학생 수가 가장 많은 학급(학생수): {}학급({}명)'.format(maxclassNo, maxCnt))
cars = ('그랜저', '소나타', '말리부', '카니발', '쏘렌토')
len()
n = 0 while n < len(cars): print(cars[n]) n += 1
flag
n = 0 flag = True while flag: print(cars[n]) n += 1 if n == len(cars): flag = False
True
n = 0 while True: print(cars[n]) n += 1 if n == len(cars): break
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)
sum = 0 avg = 0 n = 0
while n < len(studentCnts): classNo = studentCnts[n][0] cnt = studentCnts[n][1] print('{}학급 학생수: {}명'.format(classNo, cnt)) sum += cnt n += 1
print('전체 학생 수: {}명'.format(sum)) print('평균 학생 수: {}명'.format(sum / len(studentCnts)))
minScore = 60 scores = ( ('국어', 58), ('영어', 77), ('수학', 89), ('과학', 99), ('국사', 50))
n = 0 while n < len(scores): if scores[n][1] < minScore: print('과락 과목: {}, 점수: {}'.format(scores[n][0], scores[n][1])) n += 1
continue
minScore = 60 scores = ( ('국어', 58), ('영어', 77), ('수학', 89), ('과학', 99), ('국사', 50))
n = 0 while n < len(scores): if scores[n][1] >= minScore: n += 1 continue
print('과락 과목: {}, 점수: {}'.format(scores[n][0], scores[n][1])) n += 1
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17) minclassNo = 0 maxclassNo = 0 minCnt = 0 maxCnt = 0 n = 0
while n < len(studentCnts): if minCnt == 0 or minCnt > studentCnts[n][1]: minclassNo = studentCnts[n][0] minCnt = studentCnts[n][1]
if maxCnt < studentCnts[n][1]: maxclassNo = studentCnts[n][0] maxCnt = studentCnts[n][1] n += 1
print('학생 수가 가장 적은 학급(학생수): {}학급({}명)'.format(minclassNo, minCnt)) print('학생 수가 가장 많은 학급(학생수): {}학급({}명)'.format(maxclassNo, maxCnt))
키(key)와 값(value)를 이용해서 자료를 관리한다
(키는 중복 불가능, 값은 중복 가능)
'{}'를 이용해서 선언하고, '키':'값'의 형태로 아이템을 정의한다
(key에 [ ](리스트) 올수없음, ( )(튜플)가능)
(실습) 나의 정보(이름, 전공, 메일, 주소 등)를 딕셔너리에 저장하고 출력해보자
myInfo = {'이름':'박경진', '전공':'computer', '메일':'jin@naver.com', '학년':3, '주소':'대한민국 서울', '취미':['요리', '여행']} print('myInfo: {}'.format(myInfo))
딕셔너리는 키(key)를 이용해서 값(value)을 조회한다
존재하지 않는 키를 이용한 조회 시 에러(error) 발생한다
get(key)을 이용해서 값(value)을 조회 할 수 있다
나의 정보(이름, 전공, 메일, 주소 등)를 딕셔너리에 저장하고 '[]'와 'get()' 함수를 이용해서 조회하고 출력하자
myInfo = {'이름':'홍길동', '전공':'컴공', '메일':'gildong@gmail.com', '학년':3, '주소':'korea seoul', '취미':['수영', '축구']}
print(myInfo)
print(myInfo['이름']) print(myInfo['메일']) print(myInfo['취미'])
print(myInfo.get('전공')) print(myInfo.get('학년')) print(myInfo.get('주소'))
'딕셔너리이름[키(key)]=값(value)' 형태로 아이템을 추가한다
추가 하려는 키가 이미 있다면 기존 값이 변경된다
(실습) 학생 정보(이름, 학년, 메일, 주소)를 입력받아 딕셔너리에 추가해보자
studentInfo = {}
studentInfo['name'] = input('이름 입력: ') studentInfo['grade'] = input('학년 입력: ') studentInfo['mail'] = input('메일 입력: ') studentInfo['address'] = input('주소 입력: ')
print('studentInfo : {}'.format(studentInfo))
factorialDic = {}
for i in range(11): if i == 0: factorialDic[i] = 1 else: for j in range(1, (i + 1)): factorialDic[i] = factorialDic[i - 1] * j
print('factorialDic : {}'.format(factorialDic))
'딕셔너리이름[키(key)]=값(value)' 형태로 아이템을 수정한다
(실습) 학생의 시험 점수가 60점 미만이면 'F(재시험)'으로 값을 변경해보자
scores = {'kor':88, 'eng':55, 'mat':85, 'sci':57, 'his':82} print('scores : {}'.format(scores))
minScore = 60 fStr = 'F(재시험)' if scores['kor'] < minScore: scores['kor'] = fStr if scores['eng'] < minScore: scores['eng'] = fStr if scores['mat'] < minScore: scores['mat'] = fStr if scores['sci'] < minScore: scores['sci'] = fStr if scores['his'] < minScore: scores['his'] = fStr
print('scores : {}'.format(scores))
myBodyInfo = {'이름':'gildong', '몸무게':83.0, '신장':1.8} myBMI = myBodyInfo['몸무게'] / (myBodyInfo['신장'] ** 2) print('myBodyInfo: {}'.format(myBodyInfo)) print('myBMI: {}'.format(round(myBMI, 2)))
date = 0 while True: date += 1 myBodyInfo['몸무게'] = round((myBodyInfo['몸무게'] - 0.3), 2) print('몸무게: {}'.format(myBodyInfo['몸무게'])) myBodyInfo['신장'] = round((myBodyInfo['신장'] + 0.001), 3) print('신장: {}'.format(myBodyInfo['신장']))
myBMI = myBodyInfo['몸무게'] / (myBodyInfo['신장'] ** 2)
if date >= 30: break
print('myBodyInfo: {}'.format(myBodyInfo)) print('myBMI: {}'.format(round(myBMI, 2)))
전체 키(key)와 값(value)를 조회할 수 있다
(완벽한 리스트 아님)
리스트(list())로 변환하기
(완벽한 리스트)
for문을 이용한 조회
(실습) 학생의 시험 점수가 60점 미만이면 'F(재시험)'으로 값을 변경하는 코드를 keys()를 이용해서 작성해보자
scores = {'kor':88, 'eng':55, 'mat':85, 'sci':57, 'his':82} print(f'scores: {scores}')
minScore = 60 fStr = 'F(재시험)' fDic = {}
for key in scores: if scores[key] < minScore: scores[key] = fStr fDic[key] = fStr
print('scores: {}'.format(scores)) print('fDic: {}'.format(fDic))
del과 key를 이용한 item 삭제
pop()와 key를 이용한 item 삭제
(실습) 딕셔너리에 저장된 점수 중 최저 및 최고 점수를 삭제하는 프로그램을 만들어보자
scores = {'score1':8.9, 'score2':8.1, 'score3':8.5, 'score4':9.8, 'score5':8.8}
minScore = 10 minScoreKey = '' maxScore = 0 maxScoreKey = ''
for key in scores.keys(): if scores[key] < minScore: minScore = scores[key] minScoreKey = key
if scores[key] > maxScore: maxScore = scores[key] maxScoreKey = key
print('minScore : {}'.format(minScore)) print('minScoreKey : {}'.format(minScoreKey)) print('maxScore : {}'.format(maxScore)) print('maxScoreKey : {}'.format(maxScoreKey))
del scores[minScoreKey] del scores[maxScoreKey]
print('scores : {}'.format(scores))
in, not in을 사용하면 키(key) 존재 유/무 판단할 수 있다
len()를 사용하면 딕셔너리 길이(아이템 개수) 를 알 수 있다
clear()를 사용하면 모든 아이템을 삭제할 수 있다
(실습) 개인 정보에 '연락처'와 '주민등록번호'가 있다면 삭제하는 코드를 작성해보자
myInfo = {'이름':'Hong Gildong', '나이':'30', '연락처': '010-1234-5678', '주민등록번호':'840315-1234567', '주소':'대한민국 서울'}
print('myInfo: {}'.format(myInfo))
deleteItems = ['연락처', '주민등록번호']
for item in deleteItems: if (item in myInfo): del myInfo[item]
print('myInfo: {}'.format(myInfo))
리스트와 튜플을 비교해가며 특징을 알아보고 사용 가능한 기능과 불가능한 기능을 구분, 코드를 만들어본 경험이 가장 재미있었다
아직은 딕셔너리 부분이 조금 익숙하지 않고 딕셔너리 추가 부분의 0부터 10까지의 각각의 정수에 대한 팩토리얼을 딕셔너리에 추가하는 실습이 아직도 이해가 잘 가지 않는다
자료구조 부분 학습을 끝내고 들은 생각은 정말 외울게 많다는 것이다
기능들도 많고 리스트 튜플 딕셔너리 별로 다 다른 부분이 많아서 어렵다기보단 헷갈리는 것이 많았던 것 같다
내일은 자료구조 문제풀이를 할 예정이다