- 리스트를 곱셈 연산하면 아이템이 반복됨
index(item)함수로 item의 인덱스를 찾을 수 있음count(item)함수로 특정 아이템의 갯수를 확인할 수 있음del students[1]과 같이 사용해서 students 리스트의 인덱스 1 값을 삭제할 수 있음
students = ['봉석', '희수', '강훈', '기수', '별']
double = students * 2
print(double)
HSIndx = double.index('희수',2, 8)
print(HSIndx)
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}')
😆
- 리스트와 비슷하지만 변경, 수정이 불가능함
- 숫자, 문자(열), 논리형 등 모든 기본 데이터를 같이 저장할 수 있음
- 튜플에 또 다른 컨테이너 자료형 데이터를 저장할 수 있음
students[0]과 같이 사용하여 튜플 아이템 조회가 가능
students = ('봉석', '희수', '강훈', '기수', '별이')
for i in range(len(students)):
if i % 2 == 0:
print(f'인덱스가 짝수({i})인 학생: {students[i]}')
else:
print(f'인덱스가 홀수({i})인 학생: {students[i]}')
- 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}')
😲
myFavSports = ('테니스', '등산', '필라테스', '웨이트')
for item in myFavSports:
print(f'{item}')
for i in range(len(myFavSports)):
print(f'{i}: {myFavSports[i]}')
- 튜플의 결합도 리스트와 동일함
+연산자를 경우에 맞게 활용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)
😮
- 슬라이싱 방법은 리스트와 동일
- 단, 슬라이싱을 통해 데이터를 변경할 수는 없음
students = ('봉석', '희수', '강훈', '기수', '별이')
print(students[:-2])
extra = students[-2:]
print(extra)
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)
😉
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)
- 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}명)')
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}명)')