[자료구조] List와 while문

신은지·2024년 7월 8일

Data Structure

목록 보기
5/31
post-thumbnail

while문을 이용한 조회

while문을 이용하면 다양한 방법으로 아이템 조회가 가능하다.

cars = ['트랙스', '알페온', '제네시스', '아반떼']

print('---while 1번째 방법---')
n1 = 0
while n1 < len(cars):
	print(cars[n1])
    n1 += 1

print('---while 2번째 방법---')
n2 = 0
flag = True
while flag:
	print(cars[n2])
    n2 += 1
   
    if n == len(cars):
    	flag = False

print('---while 3번째 방법---')
n3 = 0
while True:
	print(cars[n3])
    n3 += 1
   
    if n == len(cars):
    	break

print('---while 4번째 방법---')
studentCnt = [[1, 19], [2, 20], [3, 22], [4, 18], [5, 21]]
n4 = 0
while n4 < len(studentCnt):
	print('{}학급 학생 수: {}'.format(studentCnt[n4][0], studentCnt[n4][1]))
    n4 += 1

💡Python으로 while문을 이용해 리스트 조회하기1

# 아래 표와 리스트를 이용해서 학급별 학생 수와 전체 학생 수 그리고 평균 학생 수를 출력
'''
1학급 : 18명, 2학급 : 19명, 3학급 : 23명, 4학급 : 21명, 5학급 : 20명, 6학급 : 22명, 7학급 : 17명
'''
school = [
    [1, 18],
    [2, 19],
    [3, 23],
    [4, 21],
    [5, 20],
    [6, 22],
    [7, 17]
]
# 학급별 학생 수와 전체 학생 수 그리고 평균 학생 수
n = 0
totalStudent = 0
while n < len(school):
    print('{}학급: {}명'.format(school[n][0],school[n][1]))
    totalStudent += school[n][1]
    n += 1
print('전체 학생 수: {}, 평균 학생 수 {:.1f}'.format(totalStudent, totalStudent/len(school)))

💡Python으로 while문을 이용해 리스트 조회하기2

# while문과 if문을 이용해서 과락 과목 출력
minScore = 60
score = [
    ['국어', 58],
    ['영어', 77],
    ['수학:', 89],
    ['과학', 99],
    ['국사', 50]
]

n = 0
while n < len(score):
    if (score[n][1] < minScore):
        print('{}과목은 {}점으로 과락입니다.'.format(score[n][0], score[n][1]))
    n += 1

💡Python으로 while문을 이용해 리스트 조회하기3

# while문을 이용해서 사용자가 국어, 영어, 수학, 과학, 국사 점수를 입력하면 과락 과목과 점수를 출력
minScore = 60

korScore = int(input('국어: '))
engScore = int(input('영어: '))
mathScore = int(input('수학: '))
sciScore = int(input('과학: '))
hisScore = int(input('국사: '))

userScore = [
    ['국어', korScore],
    ['영어', engScore],
    ['수학:', mathScore],
    ['과학', sciScore],
    ['국사', hisScore]
]

n = 0
while n < len(userScore):
    if userScore[n][1] < minScore:
        print('{}과목 {}점으로 과락'.format(userScore[n][0], userScore[n][1]))
    n += 1

💡Python으로 while문을 이용해 리스트 조회하기4

# while문을 이용해서 학급 학생 수가 가장 작은 학급과 가장 많은 학급을 출력
'''
1학급 : 18명, 2학급 : 19명, 3학급 : 23명, 4학급 : 21명, 5학급 : 20명, 6학급 : 22명, 7학급 : 17명
'''
school = [
    [1, 18],
    [2, 19],
    [3, 23],
    [4, 21],
    [5, 20],
    [6, 22],
    [7, 17]
]
minClassNo = 0; maxClassNo = 0
minStudent = 0; maxStudent = 0

n = 0
while n < len(school):
    if minStudent == 0 or minStudent > school[n][1]:
        minClassNo = school[n][0]
        minStudent = school[n][1]

    if maxStudent == 0 or maxStudent < school[n][1]:
        maxClassNo = school[n][0]
        maxStudent = school[n][1]

    n += 1

print('학생 수가 가장 적은 학급은 {}명으로 {}반입니다.'.format(minStudent, minClassNo))
print('학생 수가 가장 많은 학급은 {}명으로 {}반입니다.'.format(maxStudent, maxClassNo))





* 이 글은 제로베이스 데이터 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.

profile
I believe there is no best, only better

0개의 댓글