[Python] 자료구조

강미진·2023년 5월 1일
0

⭐ 자료구조

  • 여러 개의 데이터가 묶여 있는 자료형을 컨테이너 자료형이라고 하고, 이러한 컨테이너 자료형의 데이터 구조를 자료구조라고 한다.
  • 자료구조는 각각의 컨테이너 자료형에 따라 차이가 있다.
    ex) list, tuple, dict, set
  • 리스트는 데이터의 교체가 가능하나 튜플은 불가하다는 차이점이 있다.
  • 딕셔너리는 key : value 로 구성됨
  • 셋트는 중복된 값이 허용되지 않는다.
#리스트
students = ['홍길동','박찬호','이용규','박승철','김지은']
print(students)
print(type(students))
#튜플
jobs = ('의사','속기사','전기기사','감정평가사','회계사')
print(jobs)
print(type(jobs))
#딕셔너리
students = {'s1': '홍길동', 's2': '박찬호', 's3': '이용규', 's4': '이하늘'}
print(students)
print(type(students))
#세트
allSales = {100, 200, 500, 101}
print(allSales)
print(type(allSales))
['홍길동', '박찬호', '이용규', '박승철', '김지은']
<class 'list'>
('의사', '속기사', '전기기사', '감정평가사', '회계사')
<class 'tuple'>
{'s1': '홍길동', 's2': '박찬호', 's3': '이용규', 's4': '이하늘'}
<class 'dict'>
{200, 500, 100, 101}
<class 'set'>

📒 리스트(List)

  • []를 이용해서 선언하고, 데이터의 구분은 ,를 사용한다.
  • 숫자, 문자열, 논리형 등 모든 데이터를 같이 저장할 수 있다.
  • 리스트에는 또 다른 컨테이너 자료형 데이터를 저장할 수 있다.
    datas = [10, 20, 30, [10, 20, 30]]

📑 인덱스

  • 각 아이템에는 자동으로 인덱스가 부여된다.
    리스트 아이템들은 인덱스를 통해 조회가 가능하다.
# for구문과 인덱스로 결과 조회하기
for i in students :
    print(i)
# 인덱스 홀수, 짝수 구분해서 조회하기
for i in range(5) :
    if i % 2 == 0:
        print(f'인덱스 짝수 : students[{i}] : {students[i]}')
    else :
        print(f'인덱스 홀수 : students[{i}] : {students[i]}')
홍길동
박찬호
이용규
박승철
김지은
인덱스 짝수 : students[0] : 홍길동
인덱스 홀수 : students[1] : 박찬호
인덱스 짝수 : students[2] : 이용규
인덱스 홀수 : students[3] : 박승철
인덱스 짝수 : students[4] : 김지은
  • index()함수를 이용해 인덱스를 찾을 수 있다.
# 1부터 10까지 정수가 중복되지 않고 섞여 있을 때 행운의 숫자 7의 위치 찾기'
import random
sample_list = random.sample(range(1,11),10)
user_num = int(input('숫자 7의 위치는?'))
search_idx = sample_list.index(7)

if search_idx == user_num :
    print('빙고')
else :
    print('땡 탈락!')

print(f'sample list : {sample_list}')
print(f'search index : {search_idx}')
-- result -- 
숫자 7의 위치는? 6
땡 탈락!
sample list : [6, 1, 2, 5, 9, 7, 8, 4, 3, 10]
search index : 5

📑 아이템 개수

  • len() 함수를 이용해 리스트의 길이를 파악할 수 있다.
  • len() 함수는 문자열의 길이도 셀 수 있다.
student_len = len(students)
print(f'학생수 : {student_len}')
학생수 : 5
  • count()함수를 이용해 특정 아이템의 개수 파악할 수 있다.
# 하루동안 헌혈을 진행한 후 혈액형 별 개수를 파악하는 프로그램 제작해보자
import random
types = ['A', 'B', 'O', 'AB']
today_data = []
type_cnt = []

for i in range (100) :
    type = types[random.randrange(len(types))]
    today_data.append(type)

for type in types :
    print(f'{type}형 : {today_data.count(type)}개')
A형 : 25개
B형 : 21개
O형 : 24개
AB형 : 30개

📑 아이템 추가

  • append()insert() 함수를 이용하면 리스트에 아이템을 추가할 수 있다.
  • append() 함수는 리스트의 가장 마지막에 아이템을 추가한다.
  • insert() 함수는 기입한 인덱스 위치에 아이템을 추가한다.
print()
print('가족 구성원 리스트에 동생을 추가_append')
myfamily_age = [['아빠', 55], ['엄마', 50], ['나', 26]]
# append
myfamily_age.append(['동생', 10])
# insert
myfamily_age.insert(2,['오빠',30])
# 결과 값
for name, age in myfamily_age :
    print(f'{name}의 나이 : {age}')
가족 구성원 리스트에 동생을 추가_append
아빠의 나이 : 55
엄마의 나이 : 50
오빠의 나이 : 30
나의 나이 : 26
동생의 나이 : 10

-enumerate() 함수는 자동으로 인덱스를 붙여주며, 아이템을 열거할 때 사용한다.

sports = ['농구', '축구', '수구', '마라톤', '테니스']
for idx, value in enumerate(sports) :
    print(f'{idx} : {value}')
0 : 농구
1 : 축구
2 : 수구
3 : 마라톤
4 : 테니스
  • 문자열에도 적용할 수 있다.
str = "hello"
for idx, value in enumerate(str) :
    print(f'{idx} : {value}')
0 : h
1 : e
2 : l
3 : l
4 : o
#가장 좋아하는 스포츠가 몇 번째에 있는지 출력해보자
sports = ['농구', '축구', '수구', '마라톤', '테니스']
favorite_sport = input('가장 좋아하는 스포츠 입력 : ')
fav_sport_index = 0

for idx, value in enumerate(sports) :
    if value == favorite_sport :
        fav_sport_index = idx + 1

print(f'{favorite_sport}{fav_sport_index}번째에 존재합니다.')
-- result --
가장 좋아하는 스포츠가 몇 번째에 있는지 출력
가장 좋아하는 스포츠 입력 : 축구
축구는 2번째에 존재합니다.
# 사용자가 입력한 문자열에서 공백의 개수를 출력한다.
message = input('메시지 입력 : ')
cnt = 0
for idx, value in enumerate(message) :
    if value == ' ' :
        cnt += 1

print(f'공백 개수 : {cnt}')
-- result --
메시지 입력 : 파이선은 1991년에 발표된 인터프리터 방식의 프로그래밍 언어이다. 파이선의 강력한 라이브러리와 풍부한 생태계를 통해, 데이터를 수집하고 분석하며 시각화할 수 있다.
공백 개수 : 18
# 오름차순으로 정렬되어 있는 숫자들에 사용자가 입력한 정수를 추가하는 프로그램 제작
numbers = [1, 3, 6, 11, 45, 54, 62, 74, 85]
input_num = int(input('숫자 입력 : '))
insert_idx = 0
# for, enumerate 구문 활용
for idx, number in enumerate(numbers) :
    if insert_idx == 0 and input_num < number :
        insert_idx = idx
numbers.insert(insert_idx, input_num)
print(numbers)
숫자 입력 : 55
[1, 3, 6, 11, 45, 54, 55, 62, 74, 85]

📑 아이템 제거

  • pop()함수를 이용하면 마지막 인덱스에 해당하는 아이템을 삭제한다
  • pop(n)을 입력하면 n인덱스에 해당하는 아이템을 삭제할 수 있다.
# -- 점수표에서 최고, 최저 점수를 제외 --
player_score = [9.5, 8.9,9.2,9.8,8.8,9.0]
min_score = 0
min_score_idx = 0
max_score = 0
max_score_idx = 0
# 원본 출력
print(f'player score : {player_score}')
#최저 점수 제거
for idx, score in enumerate(player_score) :
    if idx == 0 or min_score > score :
        min_score = score
        min_score_idx = idx
print(f'최저점수 : {min_score}점')
player_score.pop(min_score_idx)
#최고 점수 제거
for idx, score in enumerate(player_score) :
    if idx == 0 or max_score < score :
        max_score = score
        max_score_idx = idx
# 결과 출력
print(f'최고점수 : {max_score}점')
player_score.pop(max_score_idx)
print(f'player score : {player_score}')
-- result --
player score : [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
최저점수 : 8.8점
최고점수 : 9.8점
player score : [9.5, 8.9, 9.2, 9.0]
  • remove()함수를 이용하면 특정 아이템을 삭제할 수 있다.
people = ['홍길동', '박찬호', '이용규', '강호동', '박승철', '이승철', '김정윤']
print(students)
students.remove('이용규')
print(students)
['홍길동', '박찬호', '이용규', '박승철', '김지은']
['홍길동', '박찬호', '박승철', '김지은']
#remove()함수 + while로 2개 이상의 데이터를 삭제
people_b = ['홍길동', '박찬호', '이용규', '강호동', '박승철', '이승철', '김정윤']
print(people_b)
# while 구문
while '강호동' in people_b : 
	#in = 강호동이라는 데이터가 people 리스트 안에 들어가면 True, 없으면 False
    # 강호동 데이터가 remove 될 때까지 반복
    people_b.remove('이용규')
    people_b.remove('이승철')
    people_b.remove('강호동')
print(people_b)
['홍길동', '박찬호', '이용규', '강호동', '박승철', '이승철', '김정윤']
['홍길동', '박찬호', '박승철', '김정윤']
  • del 키워드를 이용해도 특정아이템을 삭제할 수 있다.
jobs = ['의사','속기사','전기기사','감정평가사','회계사']
print(f'job : {jobs}')
del jobs[1]
print(f'job : {jobs}')
job : ['의사', '속기사', '전기기사', '감정평가사', '회계사']
job : ['의사', '전기기사', '감정평가사', '회계사']

📑 아이템 정렬

  • extend() 함수는 리스트와 다른 리스트를 연결한다.
  • 덧셈 연산자 +를 이용해 연결할 수도 있다.
groupA = ['A','B','C','D']
groupB = ['E','F','G']
print(f'groupA : {groupA}')
print(f'groupB : {groupB}')
groupA.extend(groupB)
print(f'groupA.extend : {groupA}')
result = groupA + groupB
print(f'result = {result}')
groupA : ['A', 'B', 'C', 'D']
groupB : ['E', 'F', 'G']
groupA.extend : ['A', 'B', 'C', 'D', 'E', 'F', 'G']
result = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'E', 'F', 'G']
  • sort() 함수를 이용하면 오름차순 정렬이 가능하다.
  • sort(reverse=False)가 디폴트 값이며, 오름차순이다.
  • sort(reverse=True)는 내림차순이다.
# 나와 친구가 좋아하는 번호를 합취되 번호가 중복되지 않게 하는 프로그램
myFavNum = [1, 3, 5, 7, 9]
friendFavNum = [2, 3, 5, 7, 11]

print(f'내가 좋아하는 번호 \t: {myFavNum}')
print(f'친구가 좋아하는 번호 : {friendFavNum}')
addList = myFavNum + friendFavNum
result = []
for number in addList :
    if number not in result :
        result.append(number)
        result.sort(reverse=False)
print(f'합한 결과 : {result}')
-- result --
내가 좋아하는 번호 	: [1, 3, 5, 7, 9]
친구가 좋아하는 번호 : [2, 3, 5, 7, 11]
합한 결과 : [1, 2, 3, 5, 7, 9, 11]
# 점수표에서 최저 및 최고 점수를 삭제하고 총점, 평균 출력
play_score = [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
print(f'player score = {play_score}')
play_score.sort()
play_score.pop(0)
play_score.pop(-1)
print(f'player score = {play_score}')

sum = 0
avg = 0

for score in play_score :
    sum += score

avg = sum / len(play_score)

print(f'총점 : {round(sum,2)}')
print(f'평균 : {round(avg,2)}')
player score = [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
player score = [8.9, 9.0, 9.2, 9.5]
총점 : 36.6
평균 : 9.15
  • reverse()함수는 아이템 순서를 뒤집는다.
# 암호해독 프로그램 제작하기
secret = '27156231'
secret_list = []
solved_list = ''

for cha in secret :
    secret_list.append(int(cha))
secret_list.reverse()
print(f'secret list : {secret_list}')

value = secret_list[0] * secret_list[1]
secret_list.insert(2,value)
value = secret_list[3] * secret_list[4]
secret_list.insert(5,value)
value = secret_list[6] * secret_list[7]
secret_list.insert(8,value)
value = secret_list[9] * secret_list[10]
secret_list.insert(-1,value)

print(f'secret list : {secret_list}')
secret list : [1, 3, 2, 6, 5, 1, 7, 2]
secret list : [1, 3, 3, 2, 6, 12, 5, 1, 5, 7, 14, 2]

📑 리스트 참조

  • for구문과 while구문을 활용하면 리스트를 참조할 수 있다.
  • for 구문 예시
# for문 + 인덱스를 이용한 리스트의 참조
cars = ['그렌저', '소나타', '말리부', '카니발', '쏘렌토']
for i in range(len(cars)) :
    print(cars[i])
print()
# 아래 방법을 사용해도 동일한 결과가 나온다. 
for car in cars :
    print(car)
그렌저
소나타
말리부
카니발
쏘렌토
# 학급별 학생 수, 전체 학생 수, 평균 학생수 도출
student_Cnt = [[1, 18],[2, 19], [3, 23], [4, 21], 
				[5, 20], [6, 22], [7, 17]]

sum = 0
avg = 0

for classNum, classCnt in student_Cnt :
    print(f'{classNum}학급 학생수 : {classCnt}명')
    sum += classCnt

print(f'전체 학생 수 : {sum}명')
print(f'평균 학생 수 : {sum / len(student_Cnt)}명')
1학급 학생수 : 18명
2학급 학생수 : 19명
3학급 학생수 : 23명
4학급 학생수 : 21명
5학급 학생수 : 20명
6학급 학생수 : 22명
7학급 학생수 : 17명
전체 학생 수 : 140명
평균 학생 수 : 20.0명
# for문과 if문을 이용한 과락 과목 출력
f_score = 60
scores = [
    ['국어', 58],
    ['영어', 77],
    ['수학', 89],
    ['과학', 99],
    ['국사', 50]
]

for item in scores :
    if item[1] < f_score :
        print(f'과락 과목 : {item[0]}, 점수 : {item[1]}')

# 아래 방법을 사용해도 동일한 결과가 나온다. 
for subject, score in scores :
    if score >= f_score : continue
    print(f'과락 과목 : {subject}, 점수 : {score}')
과락 과목 : 국어, 점수 : 58
과락 과목 : 국사, 점수 : 50

  • while구문 예시
cars = ['그랜저','소나타','말리부','카니발','쏘렌토']
n=0
flag = True
while flag :
    print(cars[n])
    n+=1
    if n == len(cars) :
        flag = False
그랜저
소나타
말리부
카니발
쏘렌토
# 학급별 학생수 + 학생이 가장 적은 학급 + 가장 많은 학급
student_Cnt = [[1, 18],[2, 19], [3, 23], [4, 21], [5, 20], [6, 22], [7, 17]]
sum = 0
avg = 0
n = 0
minCnt = 0
maxCnt = 0
minClass = 0
maxClass = 0
while n < len(student_Cnt) :
    class_num = student_Cnt[n][0]
    cnt = student_Cnt[n][1]
    print(f'{class_num}학급 학생수 : {cnt}명')
    sum += cnt

    if minCnt == 0 or minCnt > student_Cnt[n][1] :
        minClass = student_Cnt[n][0]
        minCnt = student_Cnt[n][1]
    if maxCnt < student_Cnt[n][1] :
        maxClass = student_Cnt[n][0]
        maxCnt = student_Cnt[n][1]

    n += 1

print(f'전체 학생 수 : {sum}')
print(f'평균 학생 수 : {sum/len(student_Cnt)}')
print(f'학생 수가 가장 적은 학급 : {minClass}, 학생수 : {minCnt}')
print(f'학생 수가 가장 많은 학급 : {maxClass}, 학생수 : {maxCnt}')
1학급 학생수 : 18명
2학급 학생수 : 19명
3학급 학생수 : 23명
4학급 학생수 : 21명
5학급 학생수 : 20명
6학급 학생수 : 22명
7학급 학생수 : 17명
전체 학생 수 : 140
평균 학생 수 : 20.0
학생 수가 가장 적은 학급 : 7, 학생수 : 17
학생 수가 가장 많은 학급 : 3, 학생수 : 23
# 과락 과목 출력
fail_score = 60
scores = [
    ['국어', 58],
    ['영어', 77],
    ['수학', 89],
    ['과학', 99],
    ['국사', 50]
]

n = 0
while n < len(scores) :
    if scores[n][1] >= fail_score :
        n += 1
        continue
    print(f'과락 과목 : {scores[n][0]}, 점수 : {scores[n][1]}')
    n += 1
과락 과목 : 국어, 점수 : 58
과락 과목 : 국사, 점수 : 50

📑 리스트 슬라이싱

  • [n:m]을 이용하여 리스트에서 원하는 아이템만 추출할 수 있다.
people = ['홍길동', '박찬호', '이용규', '강호동', '박승철', '이승철', '김정윤']
print(f'people : {people[2:4]}')
print(f'people : {people[:4]}')
print(f'people : {people[4:]}')
print(f'people : {people[2:-2]}')
print(f'people : {people[-5:-2]}')
print(f'people : {people[1:5:2]}')
print(f'people : {people[:5:2]}')
print(f'people : {people[::2]}')
people : ['이용규', '강호동'] → 인덱스 2번부터 4번 전까지의 값
people : ['홍길동', '박찬호', '이용규', '강호동'] → 4번 전까지의 값
people : ['박승철', '이승철', '김정윤'] → 4번부터 끝까지
people : ['이용규', '강호동', '박승철'] → 음수는 리스트 마지막에서부터 거꾸로 센다.
people : ['이용규', '강호동', '박승철']
people : ['박찬호', '강호동'] → 1번부터 5번 전까지 2단계식 슬라이싱
people : ['홍길동', '이용규', '박승철'] → 5번 전까지 2단계식 슬라이싱
people : ['홍길동', '이용규', '박승철', '김정윤'] → 2단계씩 전체 슬라이싱
  • 슬라이싱한 값만 떼어내 업데이트 할 수 있다.
people[1:4] = ['ChanHo Park', 'YongGyu Lee', 'HoDong Kang']
print(f'people : {people}')
people : ['홍길동', 'ChanHo Park', 'YongGyu Lee', 'HoDong Kang', '박승철', '이승철', '김정윤']
  • [slice(2,4)] 함수를 이용해 슬라이싱 할 수도 있다.
print(f'people : {people[slice(2,4)]}')
print(f'people : {people[slice(4)]}')
print(f'people : {people[slice(2,len(people))]}')
print(f'people : {people[slice(2,len(people)-2)]}')
people : ['이용규', '강호동']
people : ['홍길동', '박찬호', '이용규', '강호동']
people : ['이용규', '강호동', '박승철', '이승철', '김정윤']
people : ['이용규', '강호동', '박승철']

📒 튜플(Tuple)

  • 리스트와 비슷하지만 아이템 변경은 불가능하다.
  • 수정이나 삭제가 불가능하다.
  • ()를 사용해 선언하고, 데이터의 구분은 ,를 이용한다.
    students = ('홍길동', '박찬호', '이용규', '박승철', '김지은')
  • 숫자, 문자, 논리형 모두 기본 데이터를 같이 저장할 수 있다.

🏷️ 리스트 슬라이싱

  • 튜플도 리스트와 마찬가지로 아이템에 자동으로 부여되는 인덱스가 존재한다.
students = ('홍길동', '박찬호', '이용규', '박승철', '김지은')

print(f'students[0] : {students[0]}')
print(f'students[1] : {students[1]}')
print(f'students[2] : {students[2]}')
print(f'students[3] : {students[3]}')
print(f'students[4] : {students[4]}')
students[0] : 홍길동
students[1] : 박찬호
students[2] : 이용규
students[3] : 박승철
students[4] : 김지은
  • 인덱스를 활용해 데이터를 구분할 수 있다.
students = ('홍길동', '박찬호', '이용규', '박승철', '김지은')
for i in range (5) :
    if i % 2 == 0 :
        print(f'짝수 : students[{i}] : {students[i]}')

    else :
        print(f'홀수 : students[{i}] : {students[i]}')
짝수 : students[0] : 홍길동
홀수 : students[1] : 박찬호
짝수 : students[2] : 이용규
홀수 : students[3] : 박승철
짝수 : students[4] : 김지은

🏷️ in, not in 키워드

  • 해당 아이템이 있으면 in 키워드를 사용한다.
  • 해당 아이템이 컨테이너에 없으면 not in 키워드를 사용한다.
student_tuple = ('홍길동', '박찬호', '이용규', '박승철', '김지은')
search_name = input('학생 이름을 입력하세요. ')
if search_name in student_tuple :
    print(f'{search_name} 학생은 우리반 학생입니다.')
else :
    print(f'{search_name} 학생은 우리반 학생이 아닙니다.')
학생 이름을 입력하세요. 홍길동
홍길동 학생은 우리반 학생입니다.
			or
학생 이름을 입력하세요. 이승철
이승철 학생은 우리반 학생이 아닙니다.
  • 해당 키워드는 문자열에서도 사용 가능하다.
str = 'zero base 스쿨'
print('{} : {}'.format('zero', 'zero' in str))
print('{} : {}'.format('Zero', 'Zero' in str))
print('{} : {}'.format('스쿨', '스쿨' in str))
print('{} : {}'.format('스 쿨', '스 쿨' in str))
zero : True
Zero : False
스쿨 : True
스 쿨 : False
# 1부터 10까지 5개의 난수를 생성해 사용자가 입력한 숫자가 있는 지 확인
import random
ran_num = random.sample(range(1,11), 5)
user_num = int(input('숫자를 1개 입력해주세요 : '))
if user_num in ran_num :
    print('빙고')
else :
    print('다음 기회에.')
print(f'랜덤 숫자 : {ran_num}')
print(f'입력 숫자 : {user_num}')
숫자를 1개 입력해주세요 : 6
다음 기회에.
랜덤 숫자 : [8, 10, 1, 9, 7]
입력 숫자 : 6
# 비속어 필터링
wrong_word = ['쩔었다', '짭새', '꼽사리', '먹튀', '지린', '쪼개다', '뒷담']
sentence = '짭새 등장에 강도들은 모두 쩔었다. 강도들은 지린 듯 도망갔다.'
for word in wrong_word :
    if word in sentence :
        print(f'비속어 : {word}')
비속어 필터링
비속어 : 쩔었다
비속어 : 짭새
비속어 : 지린

🏷️ 튜플 길이

  • 리스트와 마찬가지로 튜플에 저장된 아이템 개수를 튜플 길이라고 한다.
  • len() 함수를 사용해 튜플 길이를 구해준다.
students = ('홍길동', '박찬호', '이용규', '박승철', '김지은')
length = len(students)
print(f'튜플 길이 : {length}')
튜플 길이 : 5
  • len()함수를 활용할 수 있는 방법은 다양하다.
students = ('홍길동', '박찬호', '이용규', '박승철', '김지은')
for i in range(len(students)) :
    print(f'students : {students[i]}')
    
# 아래 방법을 사용해도 동일한 결과가 나온다.
for i in students :
    print(f'students : {i}')
students : 홍길동
students : 박찬호
students : 이용규
students : 박승철
students : 김지은

📑 튜플의 특징

🏷️ 튜플의 결합

  • 두 개의 튜플을 결합할 수 있다.
  • 이때 extend() 함수는 튜플에서 사용할 수 없다.
    튜플은 한 번 데이터가 선언되면 그 데이터가 변경되지 않는 속성을 가지고 있기 때문이다.
  • 튜플을 ‘+’로 결합하는 것이 가능한 이유는, 그로 인해 새로운 튜플이 생성되기 때문이다.
student_a = ('홍길동', '박찬호', '이용규')
student_b = ('이승기', '김지은', '성시경')
student_c = student_a + student_b
print(student_c)
-- result -- 
('홍길동', '박찬호', '이용규', '이승기', '김지은', '성시경')
  • 튜플은 다른 데이터와의 결합이 불가하다.
    고로 다른 데이터를 튜플로 변경시켜줘야 한다.
    myNum = (1, 2, 3, 4, 5)
    myNum + 6 (X)
    myNum + (number, )
  • 이를 바탕으로 예제를 풀어보자.
# 튜플을 이용해 나와 친구가 좋아하는 번호를 합치되, 번호는 중복되지 않는다.
myFavNum = (1, 3, 5, 7, 9)
friendFavNum = (2, 3, 5, 7, 11, 13)
for number in friendFavNum :
     if number not in myFavNum :
         myFavNum = myFavNum + (number,) 
         #튜플과 튜플의 결합으로 만들어내기 위해서 ()를 사용한다.

print(f'합쳐진 번호 : {myFavNum}')
합쳐진 번호 : (1, 3, 5, 7, 9, 2, 11, 13)

🏷️ 튜플 슬라이싱

  • 리스트와 마찬가지로 [n:m]을 이용해 원하는 아이템만 뽑아낼 수 있다.
students = ('홍길동', '박찬호', '이용규', '박승철', '김지은')
print(f'students: {students}')
print(f'students: {students[2:4]}')
print(f'students: {students[:4]}')
print(f'students: {students[2:]}')
students: ('홍길동', '박찬호', '이용규', '박승철', '김지은')
students: ('이용규', '박승철')
students: ('홍길동', '박찬호', '이용규', '박승철')
students: ('이용규', '박승철', '김지은')
  • 그러나 슬라이싱을 이용해 아이템을 변경할 수는 없다.
    students[1:3] = (‘ChaHo Park’, ‘YoungGyu Lee’) [X]
  • slice() 함수를 활용해 튜플을 슬라이싱 하는 건 가능하다.

🏷️ 리스트와의 비교

  • 튜플은 아이템 추가, 변경, 삭제가 불가능 하다.append(X), pop(X)
  • 튜플은 선언할 때 괄호 생략이 가능하다.
    students = ‘홍길동’, ‘박찬호’, ‘이용규’, ‘강호동’ [O]

🏷️ 튜플 정렬

  • 튜플은 수정이 불가능하기 때문에 정렬할 때도 리스트로 변경해줘야 한다.
  • sorted 함수를 사용하면 튜플을 정렬할 수 있다.단, 리스트 자료형으로 반환된다.
students = ('홍길동', '박찬호', '이용규', '박승철', '김지은')
students = sorted(students)
print(f'students : {students}')
students : ['김지은', '박승철', '박찬호', '이용규', '홍길동']

📑 자료형 변환

  • 리스트와 튜플은 자료형 변환이 가능하다.
number = (2, 50, 0.25, 600, 1, 9, 22, 3.14, 43)
print(f'number: {number}')
print(f'number type : {type(number)}')
number = list(number)
print(f'number: {number}')
print(f'number type : {type(number)}')
number: (2, 50, 0.25, 600, 1, 9, 22, 3.14, 43)
number type : <class 'tuple'>
number: [2, 50, 0.25, 600, 1, 9, 22, 3.14, 43]
number type : <class 'list'>
  • 자료형 변환을 통해 튜플 데이터를 변경해보자.
# 점수표에서 최저, 최고 점수를 삭제하고 총점, 평균을 출력
score = 9.5, 8.9, 9.2, 9.8, 8.8, 9.0
print(f'score type : {type(score)}')
score = list(score)
print(f'score type : {type(score)}')
score.sort()
score.pop(0)
score.pop(-1)
score = tuple(score)
print(f'score = {score}')

sum = 0
avg = 0
for i in score :
    sum += i
avg = sum / len(score)

print(f'총점 : {round(sum,2)}점')
print(f'평점 : {round(avg,2)}점')
score type : <class 'tuple'>
score type : <class 'list'>
score = (8.9, 9.0, 9.2, 9.5)
총점 : 36.6점
평점 : 9.15점

📑 튜플 참조

-튜플 역시 리스트처럼for구문을 활용해 아이템을 참조할 수 있다.

studentCnt = ((1, 19), (2, 20), (3,22), (4, 18), (5, 21))
for classNo, cnt in studentCnt :
    print(f'{classNo}학급 학생수 : {cnt}')
1학급 학생수 : 19
2학급 학생수 : 20
3학급 학생수 : 22
4학급 학생수 : 18
5학급 학생수 : 21
  • for, if 사용해서 튜플을 참조해보자.
# 과락과목 출력하기
min_score = 60
scores = (
    ('국어', 58),
    ('영어', 5778),
    ('수학', 89),
    ('과학', 99),
    ('국사', 50),
)
for subject, score in scores :
    if score < min_score :
        print(f'과락 과목 : {subject}, 점수 : {score}')
과락 과목 : 국어, 점수 : 58
과락 과목 : 국사, 점수 : 50
  • while 구문을 사용해 튜플을 참조해보자
while n < len(student_Cnt) :
    classNo = student_Cnt[n][0]
    class_cnt = student_Cnt[n][1]
    sum += class_cnt
    n += 1

avg = sum / len(student_Cnt)
for class_num, cnt in student_Cnt :
    if min_class_cnt == 0 or min_class_cnt > cnt :
        min_class = class_num
        min_class_cnt = cnt

    if max_class_cnt < cnt :
        max_class = class_num
        max_class_cnt = cnt

print(f'학생이 가장 적은 학급 : {min_class}, {min_class_cnt}명')
print(f'학생이 가장 많은 학급 : {max_class}, {max_class_cnt}명')
print(f'전체 학생 수 : {round(sum,2)}명')
print(f'평균 학생 수 : {round(avg,2)}명')
가장 사람이 적은 학급, 많은 학급
학생이 가장 적은 학급 : 7, 17명
학생이 가장 많은 학급 : 3, 23명
전체 학생 수 : 141명
평균 학생 수 : 20.14명
  • while을 활용한 다양한 참조 방법들
#1
cars = ('그랜저', '소나타', '말리부', '카니발', '쏘렌토')
n = 0
while n <len(cars) :
    print(cars[n])
    n += 1

#2
print()
n = 0
flag = True
while flag :
    print(cars[n])
    n += 1

    if n == len (cars) :
        flag = False

#3
print()
n = 0
while True :
    print(cars[n])
    n += 1

    if n == len(cars) :
        break
모든 항목의 값이 동일하다.
그랜저
소나타
말리부
카니발
쏘렌토
  • while, if를 활용한 참조
# 과락 과목 출력하기
minScore = 60
scores = (
    ('국어', 58),
    ('영어', 5778),
    ('수학', 89),
    ('과학', 99),
    ('국사', 50),
)
n = 0
while n < len(scores) :
    if scores[n][1] >= minScore :
        n += 1
        continue
    print(f'과락 과목 : {scores[n][0]}, 점수 : {scores[n][1]}')
    n += 1
과락 과목 : 국어, 점수 : 58
과락 과목 : 국사, 점수 : 50

📒 딕셔너리(Dict)

  • 키(key)와 값(value)을 이용해서 자료를 관리한다.
  • 키 값은 자동으로 부여되는 것이 아니라 직접 부여한다.
  • {}를 이용해서 선언하고, 키:값의 형태로 아이템을 정의한다.
  • key에는 immutable값은 올 수 있지만, mutable 값은 올 수 없다.
    즉, 변경 가능한 [리스트] 같은 값은 key에 올 수 없다.
students = {'s1': '홍길동', 's2': '박찬호', 's3': '이용규', 's4': '이하늘', 's5': '김지은'}
print(students)
{'s1': '홍길동', 's2': '박찬호', 's3': '이용규', 's4': '이하늘', 's5': '김지은'}
  • key값으로 value값을 도출할 수 있다.
    단, 이 때 존재하지 않는 key를 작성하면 에러가 발생한다.
print('student[S1]:{}'.format(students['s1']))
print('student[S2]:{}'.format(students['s2']))
print('student[S3]:{}'.format(students['s3']))
print('student[S4]:{}'.format(students['s4']))
print('student[S5]:{}'.format(students['s5']))
student[S1]:홍길동
student[S2]:박찬호
student[S3]:이용규
student[S4]:이하늘
student[S5]:김지은

-get() 함수를 통해서도 value를 도출할 수 있다.
get()를 사용할 땐, 존재하지 않는 key를 작성해도 에러가 나지 않는다.

print(students.get('s1'))
print(students.get('s2'))
print(students.get('s3'))
print(students.get('s4'))
print(students.get('s5'))
print(students.get('s6'))
홍길동
박찬호
이용규
이하늘
김지은
None ←

📑 아이템 추가

  • 딕셔너리 이름[key] = value 형태로 딕셔너리에 아이템 추가할 수 있다.
  • 값이 중복되는 경우에는 마지막 값으로 업데이트 된다.
myInfo = {
    '이름': '000',
    '전공': '법학과',
    '메일': 'mijin@gmail.com',
    '학년': 4,
    '주소': '서울특별시',
    '취미': ['수영', '배드민턴']
}
myInfo['특기'] = '글쓰기'
myInfo['메일'] = 'kangmijin@gamil.com'

print('이름 : {}'.format(myInfo.get('이름')))
print('전공 : {}'.format(myInfo.get('전공')))
print('메일 : {}'.format(myInfo.get('메일')))
print('학년 : {}학년'.format(myInfo.get('학년')))
print('주소 : {}'.format(myInfo.get('주소')))
print('취미 : {}'.format(myInfo.get('취미')))
print('특기 : {}'.format(myInfo.get('특기')))
이름 : 000
전공 : 법학과
메일 : kangmijin@gamil.com
학년 : 4학년
주소 : 서울특별시
취미 : ['수영', '배드민턴']
특기 : 글쓰기
  1. keys(), values(), items()
  • 전체 키와 값을 조회할 수 있다.
  • items()는 키와 밸류 값이 하나로 뭉쳐저 튜플로 도출된다.
  • list()함수를 이용하면 해당 값들을 리스트로 변경할 수 있다.
  • for 함수와 함께 유용하게 활용할 수 있다.
  1. del, pop()를 이용해서 item을 삭제한다.

  2. key 존재 유/무를 in, not in으로 판단한다.

  3. len()함수를 사용해 아이템 개수를 알 수 있다.

  4. clear() : 모든 아이템을 삭제할 때 활용

profile
g'day mate

0개의 댓글