[자료구조] List와 for문

신은지·2024년 7월 8일

Data Structure

목록 보기
4/31
post-thumbnail

for문을 이용한 조회

for문을 이용하면 리스트의 아이템을 자동으로 참조할 수 있다.

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

for i in range(len(cars)):
	print(cars[i])

for car in cars:
	print(car)

for문을 이용한 내부 리스트 조회

for문을 이용하면 리스트 내부에 또 다른 리스트의 아이템을 조회할 수도 있다.

studentCnts = [[1, 19], [2, 20], [3, 22], [4, 18]]
for calssNo, cnt in studentCnts:
	print('{}학급 학생수: {}'.format(classNo, cnt))

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

# 아래 표와 리스트를 이용해서 학급별 학생 수와 전체 학생 수 그리고 평균 학생수를 출력
'''
1학급 : 18명, 2학급 : 19명, 3학급 : 23명, 4학급 : 21명, 5학급 : 20명, 6학급 : 22명, 7학급 : 17명
'''
students = [1, 18], [2, 19], [3, 23], [4, 21], [5, 20], [6, 22], [7, 17]

SumStudent = 0
totalStudent = 0

for classNo, studentCnt in students:
    print('{}학급: {}명'.format(classNo, studentCnt))
    totalStudent += studentCnt

print('전체 학생 수: {}명'.format(totalStudent))
print('평균 학생 수: {}명'.format(totalStudent / len(students)))

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

# 사용자가 국어, 영어, 수학, 과학, 국사 점수를 입력하면 과락 과목과 점수를 출력
minScore = 60
 
korScore = int(input('국어: '))
engScore = int(input('영어: '))
mathScore = int(input('수학: '))
sciScore = int(input('과학: '))
hisScore = int(input('국사: '))

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

for subject, score in userScore:
    if score < minScore:
        print('{}과목 {}점으로 과락'.format(subject, score))

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

# 아래의 표와 리스트를 이용해서 학급 학생 수가 가장 작은 학급과 가장 많은 학급을 출력
'''
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]
]

minInfo = min(school, key=lambda x: x[1])
maxInfo = max(school, key=lambda x: x[1])
print('학생 수가 가장 적은 학급은 {}명으로 {}반입니다.'.format(minInfo[1], minInfo[0]))
print('학생 수가 가장 많은 학급은 {}명으로 {}반입니다.'.format(maxInfo[1], maxInfo[0]))





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

profile
I believe there is no best, only better

0개의 댓글