[제로베이스] 데이터 사이언스 15기 - (05-19 자료 구조 스터디노트)

윤태호·2023년 5월 19일
0
post-thumbnail

오늘 수강한 강의 - 자료구조 (01 ~ 19)

01 자료구조 ~ 04 리스트의 길이

자료구조

  • 여러 개의 데이터가 묶여있는 자료형을 컨테이너 자료형이라고 하고, 이러한 컨테이너 자료형의 데이터 구조를 자료구조라고 한다

  • 자료구조는 각각의 컨테이너 자료형에 따라서 차이가 있으며, 파이썬의 대표적인 컨테이너 자료형으로는 리스트(List), 튜플(Tuple), 딕셔너리(Dic), 셋트(Set)가 있다

List

students = ['홍길동', '박찬호', '이용규', '박승철', '김지은']
print('students: {}'.format(students))

Tuple

jobs = ('의사', '속기사', '전기기사', '감정평가사', '회계사')
print('jobs: {}'.format(jobs))

Dic

scores = {'kor':88, 'eng':91, 'mat':95, 'sci':90, 'his':100}
print('scores: {}'.format(scores))

Set

allSales = {100, 150, 90, 110}
print('allSales: {}'.format(allSales))

리스트

  • 배열과 같이 여러개의 데이터를 나열한 자료구조

  • '[ ]'를 이용해서 선연하고, 데이터 구분은 ','를 이용한다

인덱스

  • 아이템에 자동으로 부여되는 번호표

  • 리스트 아이템은 인덱스를 이용해서 조회 가능하다

리스트 길이

  • 리스트에 저장된 아이템 개수

  • len()과 반복문을 이용하면 리스트의 아이템 조회가 가능하다

리스트의 길이만큼 반복하는 반복문

for i in range(len(students)):
    print('i : {}'.format(i))
    print('students[{}] : {}'.format(i, students[i]))
  • len() 함수는 리스트의 개수뿐만 아니라 문자열의 길이도 알 수 있다
str = 'Hello python!!'
print('\'Hello python!!\'의 길이 : {}'.format(len(str)))
  • item을 사용하여 더 간략하게 나타낼 수 있다
myFavoriteSports = ['수영', '배구', '야구', '조깅']
for item in myFavoriteSports:
    print(item)

05 리스트와 for문 ~ 08 리스트와 while문

리스트와 for문

  • for문을 이용하면 리스트의 아이템을 자동으로 참조할 수 있다
cars = ['그랜저', '소나타', '말리부', '카니발', '쏘렌토']
for i in range(len(cars)):
    print(cars[i])
for car in cars:
    print(car)
  • for문을 이용하면, 리스트 내부에 또 다른 리스트의 아이템을 조회할 수도 있다
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)))
  • for문과 if문 이용해서 과락 과목 출력하기
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))

리스트와 while문

  • while문을 이용하면 다양한 방법으로 아이템 조회가 가능하다
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)))
  • while문과 if문을 이용해서 과락 과목 출력하기
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
  • (실습) while문을 이용하여 학급 학생 수가 가장 작은 학급과 가장 많은 학급을 출력
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))

09 enumerate() 함수 ~ 19 리스트 나머지 기능들

enumerate() 함수

  • enumerate() 함수를 이용하면 아이템을 열거할 수 있다
sports = ['농구', '수구', '축구', '마라톤', '테니스']
for i in range(len(sports)):
    print('{} : {}'.format(i, sports[i]))

enumerate()

for idx, value in enumerate(sports):
    print('{} : {}'.format(idx, value))
  • enumerate()는 문자열에도 적용할 수 있다
str = 'Hello python.'
for idx, value in enumerate(str):
    print('{} : {}'.format(idx, value))
  • (실습) 가장 좋아하는 스포츠가 몇 번째에 있는지 출력하는 프로그램
sports = ['농구', '수구', '축구', '마라톤', '테니스']
favoriteSport = input('가장 좋아하는 스포츠 입력: ')
bestSportIdx = 0
for idx, value in enumerate(sports):
    if value == favoriteSport:
        bestSportIdx = idx + 1
print('{}(은)는 {}몇 번째에 있습니다.'.format(favoriteSport, bestSportIdx))
  • (실습) 사용자가 입력한 문자열에서 공백의 개수를 출력
message = input('메시지 입력: ')
cnt = 0
for idx, value in enumerate(message):
    if value == ' ':
        cnt += 1
print('공백 개수 : {}'.format(cnt))

리스트에 아이템 추가

  • append() 함수를 이용하면 마지막 인덱스에 아이템을 추가할 수 있다
scores = [['국어', 88], ['영어', 91]]
scores.append(['수학', 96])
print('scores : {}'.format(scores))
for subject, score in scores:
    print('과목: {} \t 점수: {}'.format(subject, score))
  • (실습) 가족 구성원의 나이가 아래와 같을 때 새로 태어난 동생을 리스트에 추가해보자
myFamilyAge = [['아빠', 40], ['엄마', 38], ['나', 9]]
myFamilyAge.append(['동생', 1])
for name, age in myFamilyAge:
    print('{}의 나이: {}'.format(name, age))

리스트의 특정 위치에 아이템 추가

  • insert() 함수를 이용하면 특정 위치(인덱스)에 아이템을 추가할 수 있다

  • (실습) 오름차순으로 정렬되어 있는 숫자들에 사용자가 입력한 정수를 추가하는 프로그램
    (단, 추가후에도 오름차순 정렬이 유지되어야 한다)

numbers = [1, 3, 6, 11, 45, 54, 62, 74, 85]
inputNumber = int(input('숫자 입력: '))
insertIdx = 0
for idx, number in enumerate(numbers):
    print(idx, number)
    if insertIdx == 0 and inputNumber < number:
        insertIdx = idx
numbers.insert(insertIdx, inputNumber)
print('numbers: {}'.format(numbers))

리스트의 아이템 삭제

  • pop() 함수를 이용하면 마지막 인덱스에 해당하는 아이템을 삭제할 수 있다

  • pop(n) 함수는 n인덱스에 해당하는 아이템을 삭제할 수 있다

  • (실습) 점수표에서 최저, 최고 점수 및 최저 점수를 삭제해보자

playerScore = [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
print('playerScore : {}'.format(playerScore))
minScore = 0
maxScore = 0
minScoreIdx = 0
maxScoreIdx = 0

최저점수

for idx, score in enumerate(playerScore):
    if idx == 0 or minScore > score:
        minScoreIdx = idx
        minScore = score
print('minScore:{}, minScoreIdx : {}'.format(minScore, minScoreIdx))
playerScore.pop(minScoreIdx)

최고점수

for idx, score in enumerate(playerScore):
    if maxScore < score:
        maxScoreIdx = idx
        maxScore = score
print('maxScore:{}, maxScoreIdx : {}'.format(maxScore, maxScoreIdx))
playerScore.pop(maxScoreIdx)
print('playerScore : {}'.format(playerScore))

리스트의 특정 아이템 삭제

  • remove() 함수를 이용하면 특정 아이템을 삭제할 수 있다

  • remove()는 한 개의 아이템만 삭제 가능하다
    만약 삭제하려는 데이터가 2개 이상이라면 while문을 이용하자

2개 이상은 while문 사용

students = ['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은', '강호동']
print(students)
while '강호동' in students:
    students.remove('강호동')
print(students)
  • (실습) 오늘 일정표에서 사용자가 입력한 일정을 삭제하는 프로그램
myList = ['마케팅 회의', '회의록 정리', '점심 약속', '월간 업무 보고', '치과 방문', '마트 장보기']
print('일정 : {}'.format(myList))
removeItem = input('삭제 대상 입력: ')
myList.remove(removeItem)
print('일정 : {}'.format(myList))
  • (실습) 시험 과목표에서 사용자가 입력한 과목을 삭제하는 프로그램
subjects = ['국어', '영어', '수학', '과학', '국사']
print('시험 과목표 : {}'.format(subjects))
removeSubject = input('삭제 과목명 입력: ')
while removeSubject in subjects:
    subjects.remove(removeSubject)
print('시험 과목표 : {}'.format(subjects))

리스트 연결(확장)

  • extend() 함수를 이용하면 리스트에 또 다른 리스트를 연결(확장) 할 수 있다 (A 리스트가 확장되는 개념)

  • 덧셈 연산자를 이용해서 리스트를 연결할 수도 있다 (A와 B가 더해져 새로운 C 리스트가 생기는 개념)

  • (실습) 나와 친구가 좋아하는 번호를 합치되, 번호가 중복되지 않게 하는 프로그램

myFavoriteNumbers = [1, 3, 5, 6, 7]
friendFavoriteNumbers = [2, 3, 5, 8, 10]
print('myFavoriteNumbers: {}'.format(myFavoriteNumbers))
print('friendFavoriteNumbers: {}'.format(friendFavoriteNumbers))
addList = myFavoriteNumbers + friendFavoriteNumbers
print('addList: {}'.format(addList))
result = []
for number in addList:
    if number not in result:
        result.append(number)
print('result: {}'.format(result))

리스트 아이템 정렬

  • sort() 함수를 이용하면 아이템을 정렬할 수 있다

    오름차순 -> sort()
    내림차순 -> sort(reverse=True)

  • 점수표에서 최저 및 최고 점수를 삭제한 후 총점과 평균을 출력해 보자

playerScore = [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
print('playerScore: {}'.format(playerScore))

정렬, 최저 및 최고 점수 삭제

playerScore.sort()
print('playerScore: {}'.format(playerScore))
playerScore.pop(0)
playerScore.pop(len(playerScore) - 1)
print('playerScore: {}'.format(playerScore))

총점

sum = 0
avg = 0
for score in playerScore:
    sum += score

평균

avg = sum / len(playerScore)
print('총점: %.2f' % sum)
print('평점: %.2f' % avg)

리스트 아이템 순서 뒤집기

  • reverse() 함수를 이용하면 아이템의 순서를 뒤집을 수 있다

  • (실습) 암호를 해독하는 프로그램
    ('27156231' -> '13326125157214')

secret = '27156231'
secretList = []
solvedList = ''
for cha in secret:
    secretList.append(int(cha))
secretList.reverse()
print(secretList)
val = secretList[0] * secretList[1]
secretList.insert(2, val)
print(secretList)
val = secretList[3] * secretList[4]
secretList.insert(5, val)
print(secretList)
val = secretList[6] * secretList[7]
secretList.insert(8, val)
print(secretList)
val = secretList[9] * secretList[10]
secretList.insert(11, val)
print(secretList)

리스트 슬라이싱

  • [n:m]을 이용하면 리스트에서 원하는 아이템만 뽑아낼 수 있다

    ex)
    [2:4] -> 2 <= n <4
    [:4] -> 0부터 3까지
    [2:] -> 2부터 끝까지
    [2:-2] -> 2부터 뒤에서 -2 앞까지
    [-5:-2] -> -5부터 -2 앞까지

  • [n:m]을 이용하면 문자열도 슬라이싱이 가능하다

str = 'abcdefghijklmnopqrstuvwxyz'
print('str length: {}'.format(len(str)))
print('str: {}'.format(str))
print('str: {}'.format(str[2:4]))
print('str: {}'.format(str[:4]))
print('str: {}'.format(str[2:]))
print('str: {}'.format(str[2:-2]))
print('str: {}'.format(str[-5:-2]))
  • 슬라이싱할 때 단계를 설정할 수 있다

ex)
[2:-2:2] -> 2부터 -2 앞까지 2개씩 a, c, e...

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]))
  • 슬라이싱을 이용하여 아이템을 변경할 수 있다
students = ['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은']
print('students : {}'.format(students))
students[1:4] = ['park chanho', 'lee yonggyu', 'gang hodong']
print('students : {}'.format(students))
  • 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)]))

리스트 나머지 기능들

  • 리스트를 곱셈 연산하면 아이템이 반복된다

    List x 2 = List List

  • index(item) 함수는 item의 인덱스를 알아낼 수 있다

    index('A') -> 몇번째 index
    index('A', 2, 6) -> 2에서 6 사이에 몇번째 index

  • (실습) 1부터 10까지의 정수가 중복되지 않고 섞여 있을 때 행운의 숫자 7의 위치를 찾자

import random
sampleList = random.sample(range(1, 11), 10)
selectIdx = int(input('숫자 7의 위치 입력: '))
searchIdx = sampleList.index(7)
if searchIdx == selectIdx:
    print('빙고!')
else:
    print('ㅜㅜ')
print('sampleList: {}'.format(sampleList))
print('searchIdx: {}'.format(searchIdx))
  • count() 함수를 이용하면 특정 아이템의 개수를 알아낼 수 있다

count('A') -> 리스트 안에 A가 몇개

  • del 키워드를 이용하면 특정 아이템을 삭제할 수 있다

del alphabets[1] -> alpahbets인덱스에 1번 인덱스 삭제

students = ['홍길동', '강호동', '박찬호', '이용규', '박승철', '강호동', '김지은']
print('students: {}'.format(students))

1번 인덱스 삭제

del students[1]
print('students: {}'.format(students))

1번부터 4번 앞까지 삭제

del students[1:4]
print('students: {}'.format(students))

2번부터 끝까지 삭제

del students[2:]
print('students: {}'.format(students))
  • (실습) 하루 동안 헌혈을 진행한 후 혈액형 별 개수를 파악하는 프로그램
import random
types = ['A', 'B', 'AB', 'O']
todayData = []
typeCnt = []

todayData에 100개의 랜덤 혈액형 입력

for i in range(100):
    type = types[random.randrange(len(types))]
    todayData.append(type)
print('todayData : {}'.format(todayData))
print('todayData length : {}'.format(len(todayData)))
for type in types:
    print('{}형 : {}개'.format(type, todayData.count(type)))

재미있었던 부분

리스트의 여러가지 함수와 기능들을 배웠는데 가짓수가 많긴 하지만 잘 익히기만하면 유용할 것 같다
재밌게 배웠다

어려웠던 부분

마지막에 실습으로 풀었던 하루 동안 헌혈을 진행한 후 혈액형 별 개수를 파악하는 프로그램은 혼자 코드를 짜보기에는 무리가 있었다
강의를 두번 봤는데도 좀 확확 넘어가는 느낌이어서 틀을 외우고 다시 혼자 짜봐야겠다

느낀점 및 내일 학습 계획

예전에 한번 훑었던 내용을 세밀하게 배우는 느낌이라 훨씬 수월하고 이해도 많이 어렵지는 않았다
직접 코드를 만들어보는 능력을 키우는게 제일 중요할 것 같다

profile
데이터 부트캠프 참여중

0개의 댓글