파이썬 자료구조 문제풀이

조지원·2023년 5월 28일
0

python

목록 보기
13/15


💻 keep going

정리하는데 시간이 오래 걸리지만 다시 한 번 복습한다 생각하고 하면 마음이 편해진다.

앞으로도 꾸준하게 정리한 것을 업로드 해야겠다.


💡 리스트 01

문제 :

1부터 사용자가 입력한 숫자까지의 약수와 소수를 리스트에 각각 저장하고, 출력하는 프로그램 만들기

inputNum = int(input("1보다 큰 정수 입력 : "))

listA = []
listB = []

# 약수

for n in range(1, inputNum + 1):
    if n  == 1:
        listA.append(n)

    else :
        if inputNum % n == 0:
            listA.append(n)

# 소수

for number in range(2, inputNum + 1):
    flag = True
    for n in range(2, number):
    # 1과 자기 자신이 아닌 약수가 또 있다.
        if number % n == 0 :             
            flag = False
            break

    if flag:
        listB.append(number)

print(listA)
print(listB)

🔥 결과 :

1보다 큰 정수 입력 : 15
[1, 3, 5, 15]
[2, 3, 5, 7, 11, 13]


💡 리스트 02

문제:

1부터 100사이에 난수 10개를 생성한 후 짝수와 홀수를 구분해서 리스트에 저장하고, 각각의 개수를 출력하는 프로그램 만들기

import random

randomlist = random.sample(range(1, 101), 10)
evens = []
odds = []

# 짝수라면
for n in randomlist:
    if n % 2 == 0 :            
        evens.append(n)
        
# 홀수라면
    else :
        odds.append(n)         


print("짝수 : {}, 개수 : {}개".format(evens, len(evens)))
print("홀수 : {}, 개수 : {}개".format(odds, len(odds)))

🔥 결과 :

짝수 : [80, 4, 76, 20, 98, 14], 개수 : 6개
홀수 : [27, 17, 11, 29], 개수 : 4


💡 리스트 03

문제 :

공원 입장료 : 1일 총 입장객이 100명이라고 할 때, 1일 전체 입장 요금을 구하는 프로그램 만들기

(단, 입장 고객의 나이는 난수를 이용한다.)

import random

visitors = []

for n in range(100):
    visitors.append(random.randint(1, 100))

print(visitors)

group1, group2, group3, group4, group5 = 0, 0, 0, 0, 0   # 한번에 초기화

for age in visitors:

    if 0 <= age <= 7 :
        group1 += 1

    elif 8 <= age <= 13:
        group2 += 1

    elif 14 <= age <= 19:
        group3 += 1

    elif 20 <= age <= 64:
        group4 += 1

    elif 65 <= age :
        group5 += 1

group1Price = group1 * 0
group2Price = group2 * 200
group3Price = group3 * 300
group4Price = group4 * 500
group5Price = group5 * 0

print("-" * 30)
print("영유아\t : {}명\t : {}원".format(group1, group1Price))
print("어린이\t : {}명\t : {}원".format(group2, group2Price))
print("청소년\t : {}명\t : {}원".format(group3, group3Price))
print("성인 \t : {}명\t : {}원".format(group4, group4Price))
print("어르신\t : {}명\t : {}원".format(group5, group5Price))
print("-" * 30)

sum = group1Price + group2Price + group3Price + group4Price + group5Price
sumFormat = format(sum, ",")

# = print("총합 : {:,}원".format(sum))
print("총합 : {}원".format(sumFormat))

🔥 결과 :

[56, 38, 80, 75, 44, 46, 40, 67, 43, 49, 66, 95, 24, 37, 20, 56, 80, 44, 67, 85, 98, 48, 64, 52, 77, 2, 71, 8, 39, 84, 44, 64, 55, 25, 29, 13, 16, 75, 78, 46, 48, 46, 24, 69, 28, 16, 14, 13, 16, 74, 79, 8, 17, 95, 13, 63, 95, 77, 79, 58, 38, 7, 75, 76, 65, 67, 87, 8, 6, 30, 51, 32, 46, 10, 45, 59, 55, 57, 96, 68, 37, 38, 82, 67, 63, 25, 49, 23, 33, 40, 1, 74, 33, 99, 74, 65, 56, 4, 47, 39]
------------------------------
영유아	 : 5: 0원
어린이	 : 7: 1400원
청소년	 : 5: 1500원
성인 	 : 49: 24500원
어르신	 : 34: 0------------------------------
총합 : 27,400

💡 리스트 04

문제 :

친구 이름 다섯명을 리스트에 저장하고 오름차순과 내림차순으로 정렬하기

friends = []

for n in range(5):
    friends.append(input("친구 이름 입력 :"))

print(friends)

# 오름차순 reverse=False 생략가능
friends.sort(reverse=False)              
print(friends)

# 내림차순
friends.sort(reverse=True)               
print(friends)

🔥 결과 :

친구 이름 입력 :박지원

친구 이름 입력 :김지원

친구 이름 입력 :이지원

친구 이름 입력 :조지원

친구 이름 입력 :하지원

['박지원', '김지원', '이지원', '조지원', '하지원']
['김지원', '박지원', '이지원', '조지원', '하지원']
['하지원', '조지원', '이지원', '박지원', '김지원']

문제 :

다음 리스트에서 중복 아이템(숫자)을 제거하는 프로그램 만들기

# set() 을 이용해서 중복 제거


numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]

print(f"numbers : {numbers}")

# 리스트 안 중복값 삭제
# -> set() : {}형태로 나오기에 list(set()) 해줘야 함

setNumbers = set(numbers)
print(f"setNumbers : {setNumbers}")

🔥 결과 :

numbers : [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
setNumbers : {1, 2, 3, 5, 7, 8, 9, 22}

문제 :

다음 리스트에서 중복 아이템(숫자)을 제거하는 프로그램 만들기

# while문을 이용해서 중복 제거

numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
idx = 0
while True:
    if idx >= len(numbers):
        break

# idx에 위치한 값이 numbers에서 2번이상 등장하는지 확인
    if numbers.count(numbers[idx]) >= 2:
# 현재 인덱스에 위치한 값을 리스트에서 제거
        numbers.remove(numbers[idx])
        continue

    idx += 1

print(f"numbers : {numbers}")

🔥 결과 :

numbers : [22, 8, 9, 5, 2, 7, 1, 3]


💡 리스트 05

문제 :

4개의 숫자 중 서로 다른 숫자 2개를 선택해서 만들 수 있는 모든 경우의 수를 출력하는 프로그램 만들기

numbers = [4, 6, 7, 9]

result = []

for n1 in numbers:
    for n2 in numbers:
        if n1 == n2:
            continue


        result.append([n1, n2])

print(f"result : {result}")
print(f"result length : {len(result)}")

🔥 결과 :

result : [[4, 6], [4, 7], [4, 9], [6, 4], [6, 7], [6, 9], [7, 4], [7, 6], [7, 9], [9, 4], [9, 6], [9, 7]]
result length : 12

순열 공식을 이용하는 방법

# 순열 공식 : n! / (n-r)!

import math

p = int(math.factorial(len(numbers)) / math.factorial(len(numbers) - 2))

print(p)

🔥 결과 :

12

문제 :

4개의 숫자 중 서로 다른 숫자 3개를 선택해서 만들 수 있는 모든 경우의 수를 출력하는 프로그램 만들기

numbers = [4, 6, 7, 9]

result = []

for n1 in numbers:
    for n2 in numbers:
        if n1 == n2:
            continue

        for n3 in numbers:
            if n3 == n1 or n3 == n2:
                continue


            result.append([n1, n2, n3])

print(result)

🔥 결과 :

[[4, 6, 7], [4, 6, 9], [4, 7, 6], [4, 7, 9], [4, 9, 6], [4, 9, 7], [6, 4, 7], [6, 4, 9], [6, 7, 4], [6, 7, 9], [6, 9, 4], [6, 9, 7], [7, 4, 6], [7, 4, 9], [7, 6, 4], [7, 6, 9], [7, 9, 4], [7, 9, 6], [9, 4, 6], [9, 4, 7], [9, 6, 4], [9, 6, 7], [9, 7, 4], [9, 7, 6]]


💡 튜플 01

문제 :

졸업할때 4.0이상의 학점을 받기 위해 길동이가 받아야 하는 4학년 1,2 학기의 최소 학점을 구해보기

scores= ((3.7, 4.2), (2.9, 4.3), (4.1, 4.2))

total = 0

for s1 in scores:
    for s2 in s1:
        total += s2

total = round(total, 1)
avg = round((total / 6), 1)
print("3학년 총학점 : {}점".format(total))
print("3학년 평균 : {}점".format(avg))

# 4.0 * 8 : 평균 4.0을 위한 전체 점수
grade4TargetScore = round((4.0 * 8 - total), 1)    
print(f"4학년 목표 총 학점 : {grade4TargetScore}")

# 4학년 1학기
minScore = round((grade4TargetScore / 2), 1)   
print(f"4학년 한 학기 최소학점 : {minScore}")

scores = list(scores)
scores.append((minScore, minScore))

scores = tuple(scores)
print(scores)

🔥 결과 :

3학년 총학점 : 23.43학년 평균 : 3.94학년 목표 총 학점 : 8.6
4학년 한 학기 최소학점 : 4.3
((3.7, 4.2), (2.9, 4.3), (4.1, 4.2), (4.3, 4.3))


💡 튜플 02

문제 :

2개의 튜플에 대해서 합집합과 교집합을 출력하기

# 방법 1

tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)


# 합집합
unionSet = set(tuple1).union(set(tuple2))
unionSet = tuple(unionSet)

print(f"합집합 : {unionSet}")

# 교집합
intersectionSet = set(tuple1).intersection(set(tuple2))
intersectionSet = tuple(intersectionSet)

print(f"교집합 : {intersectionSet}")

🔥 결과 :

합집합 : (0, 1, 2, 3, 5, 6, 7, 8, 9, 12, 17)
교집합 : (2, 3, 5, 6, 8)

문제 :

2개의 튜플에 대해서 합집합과 교집합을 출력하기

# 방법 2

tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)

# 튜플을 리스트 방식으로 먼저 바꿔준다
tempUni = list(tuple1)          
tempInter = []                

for n in tuple2:
    if n not in tempUni:
        tempUni.append(n)

    else :
        tempInter.append(n)
        
# sorted() : 오름차순으로 정렬
tempUni = tuple(sorted(tempUni))         
tempInter = tuple(sorted(tempInter))

print(f"합집합 : {(tempUni)}")
print(f"교집합 : {(tempInter)}")

🔥 결과 :

합집합 : (0, 1, 2, 3, 5, 6, 7, 8, 9, 12, 17)
교집합 : (2, 3, 5, 6, 8)

문제 :

2개의 튜플에 대해서 합집합과 교집합을 출력하기

# 방법 3

tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)

tempUni = tuple1 + tuple2
tempInter = sorted(list())
tempUni = sorted(list(tempUni))

print(f"tempUni : {tempUni}")
print(f"tempInter : {tempInter}")

idx = 0
while True :
    if idx >= len(tempUni):
        break

    if tempUni.count(tempUni[idx]) >= 2:
        tempInter.append(tempUni[idx])
        tempUni.remove(tempUni[idx])

        continue

    idx += 1

print()
print(f"tempUni : {tuple(tempUni)}")
print(f"tempInter : {tuple(tempInter)}")

🔥 결과 :

tempUni : [0, 1, 2, 2, 3, 3, 5, 5, 6, 6, 7, 8, 8, 9, 12, 17]
tempInter : []

tempUni : (0, 1, 2, 3, 5, 6, 7, 8, 9, 12, 17)
tempInter : (2, 3, 5, 6, 8)


💡 튜플 03

문제 :

시험 점수를 입력한 후 튜플에 저장하고 과목별 학점을 출력하기


kor = int(input("국어 점수 입력 :"))
eng = int(input("영어 점수 입력 :"))
mat = int(input("수학 점수 입력 :"))
sci = int(input("과학 점수 입력 :"))
his = int(input("국사 점수 입력 :"))

scores = ({"국어":kor},
          {"영어":eng},
          {"수학:":mat},
          {"과학":sci},
          {"국사":his})

print("scores : {}".format(scores))

for item in scores:
    for key in item.keys():
        if item[key] >= 90:
            item[key] = "A"

        elif item[key] >= 80:
            item[key] = "B"

        elif item[key] >= 70:
            item[key] = "C"

        elif item[key] >= 60:
            item[key] = "D"

        else :
            item[key] = "F"

print(scores)

🔥 결과 :


국어 점수 입력 :80
영어 점수 입력 :70
수학 점수 입력 :65
과학 점수 입력 :40
국사 점수 입력 :90
scores : ({'국어': 80}, {'영어': 70}, {'수학:': 65}, {'과학': 40}, {'국사': 90})
({'국어': 'B'}, {'영어': 'C'}, {'수학:': 'D'}, {'과학': 'F'}, {'국사': 'A'})

문제 :

튜플을 요구 사항에 맞춰 아이템을 슬라이스 해보기

numbers = (8.7, 9.0, 9.1, 9.2, 8.6, 9.3, 7.9, 8.1, 8.3)


# Index 0부터 3까지
print("numbers[:4] : {}".format(numbers[:4]))

# Index 2부터 4까지
print("numbers[2:5] : {}".format(numbers[2:5]))

# Index 3부터 끝까지
print("numbers[3:] : {}".format(numbers[3:]))

# Index 2부터 뒤에서 -2까지
print("numbers[2:-1] : {}".format(numbers[2:-1]))

# Index 0부터 끝까지 3단계씩
print("numbers[0::3] : {}".format(numbers[0::3]))

🔥 결과 :

numbers[:4] : (8.7, 9.0, 9.1, 9.2)
numbers[2:5] : (9.1, 9.2, 8.6)
numbers[3:] : (9.2, 8.6, 9.3, 7.9, 8.1, 8.3)
numbers[2:-1] : (9.1, 9.2, 8.6, 9.3, 7.9, 8.1)
numbers[0::3] : (8.7, 9.2, 7.9)

문제 :

최솟값, 최댓값을 구하고 Index 위치까지 구하기

numbers = (8.7, 9.0, 9.1, 9.2, 8.6, 9.3, 7.9, 8.1, 8.3)

print(f"최솟값 : {min(numbers)}")
print("최솟값 index {}".format(numbers.index(min(numbers))))

print(f"최댓값 : {max(numbers)}")
print("최댓값 index {}".format(numbers.index(max(numbers))))

🔥 결과 :

최솟값 : 7.9
최솟값 index 6
최댓값 : 9.3
최댓값 index 5


💡 튜플 04

문제 :

과일 개수에 대해서 오름차순 및 내림차순으로 정렬하기

fruits = {"수박":8}, {"포도":13}, {"참외":12}, {"사과":17}, {"자두":19}, {"자몽":15}
fruits = list(fruits)

# 현재 index
cIdx = 0

# 현재와 비교하는 index
nIdx = 1

# 마지막 index
eIdx = len(fruits) - 1

flag = True
while flag:
    curDic = fruits[cIdx]
    nextDic = fruits[nIdx]

    curDicCnt = list(curDic.values())[0]
    nextDicCnt = list(nextDic.values())[0]

    if nextDicCnt < curDicCnt:
        fruits.insert(cIdx, fruits.pop(nIdx))
        nIdx = cIdx + 1
        continue

    nIdx += 1

    if nIdx > eIdx:
        cIdx += 1
        nIdx = cIdx + 1

        if cIdx == 5:
            flag = False

print(tuple(fruits))

🔥 결과 :

({'수박': 8}, {'참외': 12}, {'포도': 13}, {'자몽': 15}, {'사과': 17}, {'자두': 19})


💡 튜플 05

문제 :

학급별 학생 수를 나타낸 튜플을 이용해서, 요구 사항에 맞는 데이터를 출력하기

studentCnt = ({"cls01":18,},
              {"cls02":21},
              {"cls03":20},
              {"cls04":19},
              {"cls05":22},
              {"cls06":20},
              {"cls07":23},
              {"cls08":17})

totalCnt = 0
minStdCnt = 0; minCls = ""
maxStdCnt = 0; maxCls = ""
deviation = []

# index값과 dic에 key, value 구함
for idx, dic in enumerate(studentCnt):

    for key, value in dic.items():
        totalCnt += value

        if minStdCnt == 0 or minStdCnt > value:
            minStdCnt = value
            minCls = key

        if maxStdCnt < value:
            maxStdCnt = value
            maxCls = key

print(f"전체 학생 수 : {totalCnt}")

avgCnt = totalCnt / len(studentCnt)

print(f"평균 학생 수 : {avgCnt}")
print(f"학생 수가 가장 적은 학급 : {minCls}({minStdCnt})")
print(f"학생 수가 가장 많은 학급 : {maxCls}({maxStdCnt})")

🔥 결과 :

전체 학생 수 : 160
평균 학생 수 : 20.0
학생 수가 가장 적은 학급 : cls08(17)
학생 수가 가장 많은 학급 : cls07(23)

문제 :

편차 구하기

studentCnt = ({"cls01":18,},
              {"cls02":21},
              {"cls03":20},
              {"cls04":19},
              {"cls05":22},
              {"cls06":20},
              {"cls07":23},
              {"cls08":17})
              

totalCnt = 0
minStdCnt = 0; minCls = ""
maxStdCnt = 0; maxCls = ""
deviation = []


# index값과 dic에 key, value 구함
for idx, dic in enumerate(studentCnt):

    for key, value in dic.items():
        totalCnt += value

        if minStdCnt == 0 or minStdCnt > value:
            minStdCnt = value
            minCls = key

        if maxStdCnt < value:
            maxStdCnt = value
            maxCls = key


avgCnt = totalCnt / len(studentCnt)

# 편차 구하기
for idx, dic in enumerate(studentCnt):
     for key, value in dic.items():
         deviation.append(value - avgCnt)

print(f"학급별 학생 편차 : {deviation}")

🔥 결과 :

학급별 학생 편차 : [-2.0, 1.0, 0.0, -1.0, 2.0, 0.0, 3.0, -3.0]


💡 딕셔너리 01

문제 :

사용자의 아이디, 비밀번호를 이용해서 로그인 프로그램을 만들기

members = {'urkpo':'0928^7$',
           'xxayv':'%2*9$91',
           'lsqvx':'!0%)&&4',
           'heums':'%@3^0%3',
           'uwcmc':'85236(&',
           'iemwv':')8!36^&',
           'sqblx':')^2)9!(',
           'jbbpy':'67269*3',
           'hjkwu':'$&@@#64',
           'fvwwy':'82$%)31'}

memID = input("ID 입력 : ")
memPW = input("PW 입력 : ")

if memID in members:
    if members[memID] == memPW:
        print("로그인 성공!!")

    else :
        print("비밀번호 확인")

🔥 결과 :

ID 입력 : xxayv
PW 입력 : %2*9$91
로그인 성공!!

문제 :

과목별 점수를 딕셔너리에 저장하고 출력하는 프로그램 만들기

subject = ["국어", "영어", "수학", "과학", "국사"]
scores = {}

for s in subject:
    score = input(s + "점수 입력 :")
    # "scores" 사전에 새로운 키-값 쌍을 추가!
    # ex) scores["국어"] = 88  (벨류값을 설정)
    scores[s] = score

print(f"과목별 점수 : {scores}")

for i in scores.items():
    print(i)

🔥 결과 :

국어점수 입력 :80
영어점수 입력 :70
수학점수 입력 :80
과학점수 입력 :65
국사점수 입력 :70
과목별 점수 : {'국어': '80', '영어': '70', '수학': '80', '과학': '65', '국사': '70'}
('국어', '80')
('영어', '70')
('수학', '80')
('과학', '65')
('국사', '70')


💡딕셔너리 02

문제 :

삼각형부터 십각형까지의 내각의 합과 내각을 딕셔너리에 저장하는 프로그램 만들기

(n각형의 내각의 합 : 180 x (n-2))

dic = {}

for n in range(3, 10):
    hap = 180 * (n - 2)
    ang = int(hap / n)
    
# dic안으로  key값 3(n) 의 value값을 [hap, ang]로 설정
    dic[n] = [hap,ang]

print(dic)

🔥 결과 :

{3: [180, 60], 4: [360, 90], 5: [540, 108], 6: [720, 120], 7: [900, 128], 8: [1080, 135], 9: [1260, 140]}

문제 :

1부터 10까지 각각의 정수에 대한 약수를 저장하는 딕셔너리를 만들고 출력하기

ic = {}

for n1 in range(1, 11):
    #반복할 때마다 새로운 "tempList" 생성
    # 따라서 n1 값에 대해 tempList가 초기화되고 해당 n1의 약수만 저장
    tempList = []

    # n1 + 1 : n1의 대한 약수
    for n2 in range(1, n1 + 1):

        # n2는 n1의 약수
        if n1 % n2 == 0:
            tempList.append(n2)

    dic[n1] = tempList

print(dic)

🔥 결과 :

{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 2, 4], 5: [1, 5], 6: [1, 2, 3, 6], 7: [1, 7], 8: [1, 2, 4, 8], 9: [1, 3, 9], 10: [1, 2, 5, 10]}


💡 딕셔너리 03

문제 :

다음 문구를 공백으로 구분하여 리스트에 저장한 후, 인덱스와 단어를 이용해서 딕셔너리에 저장하기

aboutPython = "파이썬은 1991년 프로그래머인 귀도 반 로섬이 발표한 " \
              "고급 프로그래밍 언어이다."
print(aboutPython)

splitList = aboutPython.split()
print(splitList)

dic = {}

for idx, v in enumerate(splitList):
    dic[idx] = v

print(dic)

🔥 결과 :

파이썬은 1991년 프로그래머인 귀도 반 로섬이 발표한 고급 프로그래밍 언어이다.
['파이썬은', '1991년', '프로그래머인', '귀도', '반', '로섬이', '발표한', '고급', '프로그래밍', '언어이다.']
{0: '파이썬은', 1: '1991년', 2: '프로그래머인', 3: '귀도', 4: '반', 5: '로섬이', 6: '발표한', 7: '고급', 8: '프로그래밍', 9: '언어이다.'}

문제 :

비속어를 찾고 비속어를 표준어로 변경하는 프로그램 만들기

txt = "강도는 서로 쪼개다, 짭새를 보고 빠르게 따돌리며 먹튀했다."

words = {'꺼지다':'가다',
          '쩔다':'엄청나다',
          '짭새':'경찰관',
          '꼽사리':'중간에 낀 사람',
          '먹튀':'먹고 도망',
          '지린다':'겁을 먹다',
          '쪼개다':'웃다',
          '뒷담 까다':'험담하다'}

# key값 빼내기
keys = list(words.keys())
print(keys)

for key in keys:
    if key in txt:
        print("key : {}".format(key))
        print("word[{}] : {}".format(key, words[key]))
        txt = txt.replace(key, words[key])

print(txt)

🔥 결과 :

['꺼지다', '쩔다', '짭새', '꼽사리', '먹튀', '지린다', '쪼개다', '뒷담 까다']
key : 짭새
word[짭새] : 경찰관
key : 먹튀
word[먹튀] : 먹고 도망
key : 쪼개다
word[쪼개다] : 웃다
강도는 서로 웃다, 경찰관를 보고 빠르게 따돌리며 먹고 도망했다.


💡 딕셔너리 04

문제 :

5명의 회원을 가입 받고 전체 회원 정보를 출력하는 프로그램 만들기

members = {}

n = 1
while n < 6:
    mail = input("메일 입력 : ")
    pw = input("비번 입력 : ")

    if mail in members:
       print("이미 사용 중인 메일 입니다.")
       # 중복회원이면 카운트가 되면 안된다.
       continue

    else :
        members[mail] = pw
        n += 1

# 출력
for key in members.keys():
    print(f"{key} : {members[key]}")


# 프로그램을 이용해서 특정 회원 계정을 삭제하는 프로그램

while True:
    delMail = input("삭제 계정(메일) 입력 : ")

    if delMail in members:
        delPw = input("비밀번호 입력 :")
        # members에 delMail 에 해당하는 벨류가 delPw와 같으면
        if members[delMail] == delPw:
            # members 딕셔너리에 delMail 키와 값 모두 삭제
            del members[delMail]
            print(f"{delMail} 계정 삭제 완료!")
            break
        # Pw가 일치하지 않는 경우
        else :
            print("비번 확인 요망!!")

    else :
        print("계정 확인 요망!!")

print(members)

🔥 결과 :

메일 입력 : a1@naver.com
비번 입력 : 123
메일 입력 : a2@naver.com
비번 입력 : 123
메일 입력 : a3@naver.com
비번 입력 : 123
메일 입력 : a4@naver.com
비번 입력 : 123
메일 입력 : a5@naver.com
비번 입력 : 123
a1@naver.com : 123
a2@naver.com : 123
a3@naver.com : 123
a4@naver.com : 123
a5@naver.com : 123
삭제 계정(메일) 입력 : a5@naver.com
비밀번호 입력 :123
a5@naver.com 계정 삭제 완료!
{'a1@naver.com': '123', 'a2@naver.com': '123', 'a3@naver.com': '123', 'a4@naver.com': '123'}


💡 딕셔너리 05

문제 :

학생 정보를 가장 효율적으로 저장하고 관리할 수 있는 자료구조를 선택해서 컨테이너 자료형으로 만들기

students = {'S21-0001':{'이름':'최성훈',
                        '성구분':'M',
                        '전공':'디자인',
                        '연락처':'010-1234-5678',
                        '메일':'hun@gmail.com',
                        '취미':['농구', '음악']},
            'S21-0002': {'이름': '탁영우',
                         '성구분': 'M',
                         '전공': '바리스타',
                         '연락처': '010-5678-9012',
                         '메일': 'yeong@gmail.com',
                         '취미': ['축구']},
            'S21-0003': {'이름': '황진영',
                         '성구분': 'W',
                         '전공': '음악',
                         '연락처': '010-9012-3456',
                         '메일': 'jin@gmail.com',
                         '취미': ['수영', '코딩']}}

# 딕셔너리에서 반복하면서 전체데이터를 조회할 수 있는 가장 효율적인 방법 for문
for k1 in students.keys():
    print(f"회원 번호 : {k1}")
    print()
    student = students[k1]
    # students의 벨류값에 대한 반복문
    for k2 in student.keys():
    # student[k2] : students 벨류값의 벨류값
        print("{} : {}".format(k2, student[k2]))     

studentNo = input("조회 대상 학생 번호 : ")
print("{} : {}".format(studentNo, students[studentNo]))

🔥 결과 :

회원 번호 : S21-0001

이름 : 최성훈
성구분 : M
전공 : 디자인
연락처 : 010-1234-5678
메일 : hun@gmail.com
취미 : ['농구', '음악']
회원 번호 : S21-0002

이름 : 탁영우
성구분 : M
전공 : 바리스타
연락처 : 010-5678-9012
메일 : yeong@gmail.com
취미 : ['축구']
회원 번호 : S21-0003

이름 : 황진영
성구분 : W
전공 : 음악
연락처 : 010-9012-3456
메일 : jin@gmail.com
취미 : ['수영', '코딩']
조회 대상 학생 번호 : S21-0003
S21-0003 : {'이름': '황진영', '성구분': 'W', '전공': '음악', '연락처': '010-9012-3456', '메일': 'jin@gmail.com', '취미': ['수영', '코딩']}


profile
keep going

0개의 댓글