230923_스터디노트

Sihyun Kim·2023년 9월 23일

자료구조

18~19_리스트 나머지 기능들

  • 리스트를 곱셈 연산하면 아이템이 반복됨
  • index(item) 함수로 item의 인덱스를 찾을 수 있음
  • count(item) 함수로 특정 아이템의 갯수를 확인할 수 있음
  • del students[1] 과 같이 사용해서 students 리스트의 인덱스 1 값을 삭제할 수 있음
students = ['봉석', '희수', '강훈', '기수', '별']

double = students * 2
print(double)

HSIndx = double.index('희수',2, 8)
print(HSIndx)
  • 실습 (10까지의 랜덤 숫자 중 7의 위치 찾기)
import random

sampleList = random.sample(range(1,11), 10)

userIdx = int(input('숫자 7의 위치(인덱스)는 어디일까요?\t'))
searchIdx = sampleList.index(7)

if userIdx == searchIdx:
    print('빙고!')

else:
    print('실패...')

print(sampleList)
print(f'7의 위치: {searchIdx}')
  • 혈액형 랜덤 분배

😆

  • for문을 사용해서 random 돌리기!
  • 리스트도 random 추출이 가능함!

20_튜플(Tuple)

  • 리스트와 비슷하지만 변경, 수정이 불가능함
  • 숫자, 문자(열), 논리형 등 모든 기본 데이터를 같이 저장할 수 있음
  • 튜플에 또 다른 컨테이너 자료형 데이터를 저장할 수 있음

21_튜플 아이템 조회

  • students[0]과 같이 사용하여 튜플 아이템 조회가 가능
students = ('봉석', '희수', '강훈', '기수', '별이')

for i in range(len(students)):
    if i % 2  == 0:
        print(f'인덱스가 짝수({i})인 학생: {students[i]}')
    else:
        print(f'인덱스가 홀수({i})인 학생: {students[i]}')

22_in과 not in 키워드

  • in, not in 키워드를 이용하면 아이템의 존재 유무 확인 가능
import random

sampleList = random.sample(range(1, 11), 5)

userN = int(input('1~10 숫자 입력 (확률 50%): '))

if userN in sampleList:
    print('빙고!')
else:
    print('실패...')

print(f'List: {sampleList}')

😲

  • random 다음에 sample, randint, randrange, sample(range(x,y), z) 등..
    뭐를 써야 할지 정확히 알기!

23_튜플 길이

myFavSports = ('테니스', '등산', '필라테스', '웨이트')

for item in myFavSports:
    print(f'{item}')

for i in range(len(myFavSports)):
    print(f'{i}: {myFavSports[i]}')

24_튜플 결합

  • 튜플의 결합도 리스트와 동일함
  • + 연산자를 경우에 맞게 활용
  • extend() 연산자는 쓸 수 없음 (∵ 튜플은 수정이 안되므로)
myfavNum = (1, 2, 5, 7, 9)
friendNum = (2, 3, 5, 8, 9)

plusList = myfavNum + friendNum

newList = ()

for item in plusList:
    if item not in newList:
        newList = newList + (item, )
    else:
        pass

print(newList)

😮

  • 튜플은 수정이 어려우니 append함수도 못 쓰고, +로 뒤에 붙여줄 수 밖에 없음!

25_튜플 슬라이싱

  • 슬라이싱 방법은 리스트와 동일
  • 단, 슬라이싱을 통해 데이터를 변경할 수는 없음
students = ('봉석', '희수', '강훈', '기수', '별이')

print(students[:-2])

extra = students[-2:]
print(extra)

26_리스트와 튜플

  • 튜플은 리스트와 달리 아이템 추가, 변경, 삭제가 불가
  • 튜플은 선언 시 괄호 생략이 가능
  • 리스트와 튜플은 서로 자료형 변환이 가능
scores = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)

scores = list(scores)
scores.sort()
scores.pop(0)
scores.pop(len(scores)-1)
scores = tuple(scores)

sumN = 0; avg = 0

for score in scores:
    sumN += score

avg = sumN / len(scores)

print('총점: %.2f' % sumN)
print('평균: %.2f' % avg)

😉

  • 튜플 아이템의 삭제나 변경이 필요할 때는 리스트로 잠시 변환해서 처리해주고 다시 튜플로!

27_튜플 아이템 정렬

  • sorted() 를 활용하면 튜플을 리스트로 변경하며 오름차순 정렬을 해줌
scores = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)

sortedScores = sorted(scores)

sortedScores.pop(0)
sortedScores.pop(len(sortedScores)-1)

28~29_튜플과 for문

  • for문을 이용하면 튜플의 아이템을 자동으로 참조할 수 있음
minScore = 60

scoreKor = int(input('국어 점수: '))
scoreEng = int(input('영어 점수: '))
scoreMat = int(input('수학 점수: '))
scoreSci = int(input('과학 점수: '))
scoreHis = int(input('국사 점수: '))

scores = ('국어', scoreKor), ('영어', scoreEng), ('수학', scoreMat), ('과학', scoreSci), ('국사', scoreHis)

for sub, score in scores:
    if score < minScore:
        print(f'과락 과목: {sub}, 점수: {score}')
stdCnt = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

minClass = 0; minCnt = 0
maxClass = 0; maxCnt = 0

for classNo, cnt in stdCnt:

    if minCnt == 0 or cnt < minCnt:
        minClass = classNo
        minCnt = cnt

    if cnt > maxCnt:
        maxClass = classNo
        maxCnt = cnt

print(f'학생 수가 가장 적은 학급: {minClass}학급 ({minCnt}명)')
print(f'학생 수가 가장 많은 학급: {maxClass}학급 ({maxCnt}명)')

30~31_튜플과 while문

stdCnt = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

sumN = 0; avg = 0
n = 0

while n < len(stdCnt):
    sumN += stdCnt[n][1]
    print('{}학급 학생수: {}명'.format(stdCnt[n][0], stdCnt[n][1]))

    n += 1

avg = sumN / len(stdCnt)

print(f'전체 학생수: {sumN}명')
print(f'평균 학생수: {avg}명')
stdCnt = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)

minClass = 0; minCnt = 0
maxClass = 0; maxCnt = 0

n = 0
while n < len(stdCnt):
    if minClass == 0 or stdCnt[n][1] < minCnt:
        minClass = stdCnt[n][0]
        minCnt = stdCnt[n][1]

    elif stdCnt[n][1] > maxCnt:
        maxClass = stdCnt[n][0]
        maxCnt = stdCnt[n][1]

    n += 1

print(f'학생 수가 가장 적은 학급: {minClass}학급({minCnt}명)')
print(f'학생 수가 가장 많은 학급: {maxClass}학급({maxCnt}명)')
profile
문과이과예체능통합형인재

0개의 댓글