본문 바로가기
파이썬 이야기

Part 18. 집합 자료형

by 핸들이없는8톤트럭 2022. 7. 25.
반응형

집합 자료형은 순서가 없으며, 중복이 허용되지 않습니다. 또한, hashable 자료형만 삽입할 수 있는데요. hashable data는 입력을 정수로 바꾸는 동작을 가능한 data를 의미합니다.

 

# 집합

print("집합의 생성")
x= set() # 비어있는 집합의 생성
print(f'x={x}', type(x))
x= {1, 5, 2, 3 ,6, 7, 9}
print(f'x={x}', type(x))

x= [10, 10, 30, 50, 60, 60] #리스트
print(f'x={x}', type(x))
y = set(x) # 리스트 --> 집합
print(f'y={y}', type(y)) # 중복된 자료 제거됨

x= (10,10, 30, 50, 60) # 튜플
print(f'x={x}', type(x))
y = set(x) # 튜플로부터 집합을 생성
print(f'y={y}', type(y))

print()
print('집합에 자료 추가하기')
x= set()
print(f'x={x}', type(x))
x.add(19)
x.add(20)
x.add(24)
print(f'x={x}', type(x))
x.update([1,2,3,4]) # 리스트, 튜플, 집합을 이용해서 추가가능
print(f'x={x}', type(x))

print()
print('집합에서 자료 제거하기')
x= {10,20,30,40,50}
print(f'x={x}', type(x))
x.remove(20) # 집합은 인덱스가 없어서 인덱스를 이용해서 제거 불가
print(f'x={x}', type(x))

print()
print("집합끼리 연산하기")
a = {1,2,3,4}
b= {3,4,5,6}
print(a.intersection(b)) # a와 b의 교집합
print('교집합', a&b) # a와 b의 교집합
print('합집합', a.union(b)) # a와 b의 합집합
print('합집합', a|b) # a와 b의 합집합
print('차집합(a-b)', a-b) # a와 b의 합집합
print('차집합(a-b)', a.difference(b)) # a와 b의 합집합
print('대칭차집합', a^b) # a-b U b-a

 

 

 

 

딕셔너리 자료형은 key와 value의 쌍으로 이루어진 자료형입니다. key는 중복을 허용하지 않고, value는 중복해서 값을 쓸 수 있습니다. key는 집합과 마찬가지로 hashable자료형을 사용해야 합니다.

 

print()
print("딕셔너리의 생성")
x=dict() #비어있는 딕셔너리의 생성
print(f'x={x}', type(x))
x= {} #비어있는 딕셔너리의 생성
print(f'x={x}', type(x))

x= {'apple':10, 'banana':20} #key : value
print(f'x={x}', type(x))

x= dict(apple=10,banana=20,mango='x') # 모든 키가 문자열인 경우 dict로 초기화가능
print(f'x={x}', type(x))

print()
print("딕셔너리 요소에 접근")
x = {1:20, 2 : 30, 'key1' : 'value'}
print(x[1])
print(x['key1'])

print()
print("딕셔너리 요소 수정/추가 제거")
x= {1:20, 2:30,}
x[1] = 230 # 이미 딕셔너리에 있는 key에 대입하면, 값을 수정
print(f'x={x}',type(x))
del x[1] # 리스트와 제거하는 방법과 유사
print(f'x={x}', type(x))

y= {2:50,
    'key1':10,
    10:20,
    100:30}
x.update(y)
print(f'x={x}', type(x))

print()
print('딕셔너리의 기능')
x= { 1:10, 2: 20, 3 : 30}
print(x.keys()) #딕셔너리의 모든 키 반환
print(x.values()) #딕셔너리의 모든 값 변환
print(len(x)) #딕셔너리에 속한 키값쌍의 수
print(3 in x) #딕셔너리에 키가 있는지 확인
print(30 in x) #딕셔너리에 키가 있는지 확인
x.clear()
print(f'x={x}', type(x))

print()
print('해쉬(Hash)')
print(hash('abcd'))
print(hash(523))
# print(hash([124,1245])) 리스트는 해쉬불가능
print(hash((10,20))) #튜플은 해쉬 가능

 

 

 

 

 

 

반응형

댓글