01 자료구조란 ~ 38 딕셔너리 유용한 기능
: 여러 개의 데이터가 묶여있는 자료형을 컨테이너 자료형이라고 하고, 이러한 컨테이너 자료형의 데이터 구조를 자료구조라고 한다.
list
, tuple
, dic
, set
students = ['A', 'B', 'C', 'D'] #list
jobs = ('의사', '속기사') #tuple
scores = {'kor':88, 'eng':91} #dic
allSales = {100, 150, 90} #set
len(리스트)
for문을 이용한 내부 리스트 조회
studentCnts = [[1, 18], [2, 19], [3, 23], [4, 21], [5, 20], [6, 22], [7, 17]]
sum = 0
avg = 0
for classNo, cnt in studentCnts:
print(f'{classNo}학급 학생 수: {cnt}명')
sum += cnt
print(f'전체 학생 수: {sum}명')
print(f'평균 학생 수: {sum/len(studentCnts)}명')
sports = ['농구', '수구', '축구', '마라톤', '테니스']
for i in range(len(sports)):
print(f'{i}: {sports[i]}')
==
for idx, value in enumerate(sports):
print(f'{idx}: {value}')
// enumerate()는 문자열에도 적용 가능.
message = input('메시지 입력: ')
cnt = 0
for idx, value in enumerate(message):
if value == ' ':
cnt += 1
print(f'공백 개수: {cnt}')
list.append(item)
, list.insert(i, item)
pop()
: 마지막 인덱스 삭제, pop(i)
: 인덱스 i 아이템 삭제remove(item)
extend()
, +
: 리스트에 다른 리스트 연결sort()
: 오름차순 정렬, sort(reverst=True)
: 내림차순 정렬reverse()
: 순서 뒤집기[2:4]
== (2<=n<4), slice()
#슬라이싱
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(f'numbers: {numbers[2:-2]}')
print(f'numbers: {numbers[2:-2:2]}')
print(f'numbers: {numbers[:-2:2]}')
print(f'numbers: {numbers[::2]}')
index(item)
, count(item)
, del listname[index]
'()'를 이용해서 선언, 아이템 변경 불가능.
in
, not in
키워드: 아이템의 존재 유무 확인. (문자열에도 사용 가능)studentsTuple = ('a', 'b', 'c', 'd')
searchName = input('학생 이름 입력: ')
if searchName in studentsTuple:
print(f'{searchName}은 우리 반 학생입니다. ')
else:
print(f'{searchName}은 우리 반 학생이 아닙니다. ')
extend()
함수 사용 불가능.
- 튜플은 리스트와 달리 아이템 추가, 변경, 삭제가 불가능하다.
- 튜플은 선언시 괄호 생략이 가능하다.
students = 'a', 'b', 'c', 'd' print(students) print(type(students)) >>> ('a', 'b', 'c', 'd') <class 'tuple'>
- 리스트와 튜플은 자료형 변환이 가능하다.
- 튜플은 데이터를 변경할 수 없기 때문에 정렬하려면 list으로 전환해야 한다.
sorted()
함수를 사용하여 튜플을 정렬 가능하지만 list 자료형을 반환한다.sortedList = sorted(tuple1)
: 키(key)와 값(value)를 이용해서 자료를 관리한다.
{}를 이용해서 선언, '키:값'의 형태
key와 value에는 컨테이너 자료형도 올 수 있다.
key에 immutable은 올 수 있지만 mutable은 올 수 없다.
immutable: 변경 불가능한 객체, ex)
int
,string
,tuple
등
mutable: 변경 가능한 객체, ex)list
,dict
id(obj)
로 확인
key를 이용해서 값(value)를 조회한다.
students = {'s1':'a', 's2':'b', 's3':'c', 's4':'d'}
print(students['s1'])
KeyError: 's6'
students.get('s1')
# get(key): 존재하지 않는 키를 이용해 조회 시 에러 발생하지 않음.
# None 반환
dictName['key'] = 'value'
# 팩토리얼 추가
factorialDic = {}
for i in range(11):
if i == 0:
factorialDic[i] = 1
else:
for j in range(1, (i+1)):
factorialDic[i] = factorialDic[i-1] * j
print(f'factorialDic: {factorialDic}')
memInfo = {'이름':'홍길동', '메일':'gildong@gmail.com', '학년':3, '취미':['농구', '게임']}
ks = memInfo.keys()
vs = memInfo.values()
items = memInfo.items()
print(f'ks: {ks}')
print(f'ks type: {type(ks)}\n') #<class 'dict_keys'>
print(f'vs: {vs}')
print(f'vs type: {type(vs)}\n') #<class 'dict_values'>
print(f'items: {items}')
print(f'items type: {type(items)}\n') #<class 'dict_items'>
del dicName['key']
, dicName.pop('item')
in
, not in
, len()
, clear()