set자료형의 특징
1. 순서를 가지지 않는다.
a=set([4,9,2])
b=set['abc')
print a
print b
>>
set([2,4,9])
set(['a','c','e'])
즉, 결과값을 보면 a의 경우 리스트를 입력받아 set자료형을 만들었고,
b의 경우 문자열을 입력받아 문자들을 하나의 인자로 인식하여 집합을 만든다.
결과처럼 입력 순서대로 출력되는것은 아니다.
2. 중복을 허용하지 않는다.
a=set('aabbcc')
print a
>> set(['a','c','b'])
3. 인덱싱이 되지 않기 때문에 set 자료형에 접근 방법
a=set('aabbcc')
print list(a)[0]
print list(a)[1]
print list(a)[2]
print tuple(a)[0]
print tuple(a)[1]
print tuple(a)[2]
>>
a
c
b
a
c
b
4. set:교집합
a=set(['a',9,'c',2])
b=set([1,'c',2,'a'])
a&b
>>> {'a','c',2}
a=set(['a',9,'c',2])
b=set([1,'c',2,'a'])
a.intersaction(b)
>>> {'a','c',2}
5. set:합집합
a=set(['a',9,'c',2])
b=set([1,'c',2,'a'])
print a|b
print a.union(b)
>>>
set(['a',1,'c',2,'9'])
set(['a',1,'c',2,'9'])
6. set:차집합
a=set(['a',9,'c',2])
b=set([1,'c',2,'a'])
a-b
>>>set([1,9])
a=set(['a',9,'c',2])
b=set([1,'c',2,'a'])
print a.difference(b)
print b.difference(a)
>>>
set([1,9])
set([1,9])
7. remove (set 원소 삭제)
a=set([1,2,3])
a.remove(1)
print a
>>> set([2,3])
8. add (set 하나 원소 추가)
a=set([2,3])
a.add(1)
print a
>>> set([2,3,1])
9. update (set 자료형 여러 원소 추가)
a=set([2,3])
a.update([5,4])
print a
>>> set([2,3,5,4])
10. set pop (임의의 요소를 갖고 온 후 제거)
a = {1,2,3,4,5}
print(f'poptarget : {a}')
print(f'poplist : {a.pop()}')
print(f'poptarget : {a}')
>>>
poptarget : {1, 2, 3, 4, 5}
poplist : 1
poptarget : {2, 3, 4, 5} // 1의 요소가 삭제 되었음을 알 수 있다.
11. set clear(모든 요소 제거)
a = {1,2,3,4,5}
print(f'poptarget : {a}')
a.clear()
print(f'poptarget : {a}')
>>>
poptarget : {1, 2, 3, 4, 5}
poptarget : set()
12. set in(내부에 요소가 있는지 확인)
a = {1,2,3,4,5}
print(f'poptarget : {a}')
if 1 in a:
print('집합 a의 내부에 "1"이 존재합니다.')
else:
print('집합 a의 내부에 "1"이 존재하지 않습니다..')
>>>
poptarget : {1, 2, 3, 4, 5}
집합 a의 내부에 "1"이 존재합니다.
13. set len(집합 길이 확인)
a = {1,2,3,4,5}
print(f'poptarget : {a}')
print(f'pop길이:{len(a)}')
>>>
poptarget : {1, 2, 3, 4, 5}
pop길이:5