[Python 기초] 04-2 자료구조

홍랑·2021년 10월 22일
0

Python

목록 보기
6/6
*using Python - PyCharm Community Edition

📌 tuple

  • list와 비슷하지만 아이템 변경, 삭제, 추가 불가
  • () 를 이용해서 선언하고 , 로 데이터 구분
studentL = ['유태오', '이종원', '송강', '정호연', '김나영']
studentT = ('유태오', '이종원', '송강', '정호연', '김나영')

print(studentL)	# ['유태오', '이종원', '송강', '정호연', '김나영']
print(studentT)	# ('유태오', '이종원', '송강', '정호연', '김나영')

tuple 아이템 조회

  • list처럼 인덱스가 부여됨
studentT = ('유태오', '이종원', '송강', '정호연', '김나영')
numT = (10, 20, 30, 40, 50)

print(studentT[1])	# 이종원
print(numT[3])		# 40

in / not in

  • 아이템 존재의 유무 확인
studentT = ('유태오', '이종원', '송강', '정호연', '김나영')
scName = input("이름 입력: ")

# 들어 있으면 T, 없으면 F
if scName in studentT:		
    print('{} in tuple'.format(scName))
else:
    print('{} not in tuple'.format(scName))
    
# 들어 있으면 F, 없으면 T
if scName not in studentT:	
    print('{} not in tuple'.format(scName))
else:
    print('{} in tuple'.format(scName))

tuple 길이

  • len()
studentT = ('유태오', '이종원', '송강', '정호연', '김나영')

# len()을 활용해 아이템 조회 가능
for i in range(len(studentT)):
    print('i : {}'.format(i))
    print('studentT[{}] : {}'.format(i, studentT[i]))

📚 튜플 결합

  • 덧셈기호(+)로 두 개의 튜플 결합
  • 아이템을 수정할 수 없고 새로운 튜플을 만드는 것
student1 = ('유태오', '이종원', '송강')
student2 = ('정호연', '김나영')

students = student1 + student2
print(students)	# ('유태오', '이종원', '송강', '정호연', '김나영')

# 숫자가 중복되지 않게 결합하기
myNum = (1, 3, 5, 7, 9)
yrNum = (2, 4, 5, 8, 9, 10)

for num in yrNum:
    if num not in myNum:
        myNum = myNum + (num, )

print(myNum)	# (1, 3, 5, 7, 9, 2, 4, 8, 10)

📚 튜플 슬라이싱

  • [n:m]을 이용해 원하는 아이템 추출
studentT = ('유태오', '이종원', '송강', '정호연', '김나영')
print(studentT[0:2])	# ('유태오', '이종원')
print(studentT[:4])	# ('유태오', '이종원', '송강', '정호연')
print(studentT[3:])	# ('정호연', '김나영')
print(studentT[1:-1])	# ('이종원', '송강', '정호연')

num = (2, 50, 0.12, 1, 9, 7, 17)
print(num[2:-3])	# (0.12, 1)
print(num[:4])		# (2, 50, 0.12, 1)
print(num[::2])		# (2, 0.12, 9, 17)

📚 리스트 - 튜플 변환

# 튜플을 이용한 점수표에서 최고, 최저 점수를 삭제한 후 총점과 평균 출력
playerScore = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)

# 값 변경을 위해 리스트로 변환
playerScore = list(playerScore)
playerScore.sort()

# 최저 점수 삭제
playerScore.pop(0)
# 최고 점수 삭제
playerScore.pop(len(playerScore) - 1)

# 값 보호를 위해 튜플로 변환
playerScore = tuple(playerScore)

sum = 0
avg = 0
for s in playerScore:
    sum += s
avg = sum / len(playerScore)

print('total: %.2f' % sum)	# total: 36.60
print('average: %.2f' % avg)	# average: 9.15

📚 튜플 정렬

  • 튜플은 수정이 불가
  • 리스트로 변환 후 sort()
  • sorted(): 리스트 자료형을 반환하므로 바로 적용 가능
studentT = ('유태오', '이종원', '송강', '정호연', '김나영')
srotedST = sorted(studentT)
print(srotedST)	# ['김나영', '송강', '유태오', '이종원', '정호연']

📚 튜플과 반복문

for문을 이용한 조회(참조)

studentT = ('유태오', '이종원', '송강', '정호연', '김나영')
for student in studentT:
    print(student)
    
# 과락 과목 출력
minScore = 60
scores = (
    ('국어', 58),
    ('영어', 77),
    ('수학', 89),
    ('과학', 99),
    ('국사', 50))

for subject, score in scores:
    if score < minScore:
        print('과락 과목: {}, 점수: {}'.format(subject, score))
        # 과락 과목: 국어, 점수: 58
	# 과락 과목: 국사, 점수: 50

while문을 이용한 조회(참조)

cars = ('그랜저', '소나타', '말리부', '카니발', '쏘렌토')
n = 0
flag = True

while flag:
    print(cars[n])
    n += 1

    if n == len(cars):
        flag = False
        
# 과락 과목 출력
minScore = 60
scores = (
    ('국어', 58),
    ('영어', 77),
    ('수학', 89),
    ('과학', 99),
    ('국사', 50))
    
n = 0
while n < len(scores):
    if scores[n][1] < minScore:
        print('과락 과목: {}, 점수: {}'.format(scores[n][0], scores[n][1]))
    n += 1


📌 Dictionary

  • 키(key)와 값(value)을 이용해 자료 관리
  • 인덱스가 없고 키(key)가 인덱스를 대신하는 셈
  • 키(key)는 중복되지 않아야 하고 immutable 해야 함
  • {키:값}
  • 숫자, 문자(열), 논리형 뿐만 아니라 컨테이너 자료형도 가능
students = {
    's1':'이종원', 
    's2':'유태오', 
    's3':'김나영', 
    's4':['정호연', '새벽']
}

딕셔너리 조회

  • key를 이용해서 value를 조회
  • get(): value 조회 가능, 없는 key를 불러도 오류나지 않고 None 반환
students = {
    's1':'이종원',
    's2':'유태오',
    's3':'김나영'
}
print(students['s1'])		# 이종원
print(students['s2'])		# 유태오
print(students['s3'])		# 김나영
print(students.get('s1'))	# 이종원
print(students.get('100'))	# None

딕셔너리에 아이템 추가

  • dict[key] = value 형태로 추가
myInfo = {}

myInfo["name"] = 'Hong'
myInfo["mail"] = 'hhhh@naver.com'
myInfo["address"] = 'Korea, Seoul'
myInfo["hobby"] = ['cooking', 'painting']

print(myInfo)
# {'name': 'Hong', 'mail': 'hhhh@naver.com', 'address': 'Korea, Seoul', 'hobby': ['cooking', 'painting']}

# 딕셔너리 아이템 수정시 원하는 key에 새로운 value 할당
myInfo["mail"] = 'oooo@gmail.com'
print(myInfo)
# {'name': 'Hong', 'mail': 'oooo@gmail.com', 'address': 'Korea, Seoul', 'hobby': ['cooking', 'painting']}

📚 keys(), values()

  • 전체 키와 값을 조회
  • list()로 변환해 활용
myInfo = {}
myInfo["name"] = 'Hong'
myInfo["mail"] = 'hhhh@naver.com'
myInfo["address"] = 'Korea, Seoul'
myInfo["hobby"] = ['cooking', 'painting']

for key in myInfo.keys():
    print(f'{key}: {myInfo[key]}')

📚 del, pop()

  • item 삭제에 활용
myInfo = {
    "name":'Hong',
    "mail":'hhhh@naver.com',
    "address":'Korea, Seoul',
    "hobby":['cooking', 'painting']
}

del myInfo['name']
print(myInfo)
# {'mail': 'hhhh@naver.com', 'address': 'Korea, Seoul', 'hobby': ['cooking', 'painting']}

returnValue = myInfo.pop('name')
print(myInfo)
# {'mail': 'hhhh@naver.com', 'address': 'Korea, Seoul', 'hobby': ['cooking', 'painting']}
print(returnValue)
# Hong

📚 in, len(), clear()

in, not in

  • key 존재 유무 파악
myInfo = {
    "name":'Hong',
    "mail":'hhhh@naver.com',
    "address":'Korea, Seoul',
    "hobby":['cooking', 'painting']
}
print('name' in myInfo)		# True
print('name' not in myInfo)	# False

len()

  • 딕셔너리 길이 파악
myInfo = {
    "name":'Hong',
    "mail":'hhhh@naver.com',
    "address":'Korea, Seoul',
    "hobby":['cooking', 'painting']
}
print('len(myInfo) : {}'.format(len(myInfo)))
# len(myInfo) : 4

clear()

  • 모든 아이템 삭제
myInfo = {
    "name":'Hong',
    "mail":'hhhh@naver.com',
    "address":'Korea, Seoul',
    "hobby":['cooking', 'painting']
}
myInfo.clear()
print(myInfo)	# {} 빈 딕셔너리 출력
profile
호랑이 기운이 솟아나요🐯

0개의 댓글