Set
python에서 set을 사용해신 적이 있나요.
저는 예전에 중복값을 제거하려고 사용한 적이 있습니다.
그 당시에 의문이 들었죠 Set은 왜 중복값이 안들어 가는가..
그이유는 set이 값을 저장할때 Hash값으로 저장하기 때문입니다.
그렇다면 언제 Set을 사용할 까요?
1. 중복된 값을 골라내야 할때
2. 빠른 look up을 해야 할때 그러면서 순서는 상관 없을때
Set의 연산자
1. union
intro = {"내", "이", "름"}
name = {"홍", "길","동"}
# Union using union()
# function
person = intro.union(name)
print(" union 실습 ")
print(person)
2. intersection
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
# Intersection using
# intersection() function
set3 = set1.intersection(set2)
print("Intersection using intersection() function")
print(set3)
# Intersection using
# "&" operator
set3 = set1 & set2
print("\nIntersection using '&' operator")
print(set3)
set1 = (0,1,2,3,4)
set2 = (3,4,5,6,7,8)
set1과 set2의 &연산자 결과는 3,4이다.
이와 같이 연산을 이용해서 찾을 수도 있다.
3. difference(여집합)
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
# difference using
# difference() function
set3 = set1.difference(set2)
print("difference using difference() function")
print(set3)
# difference using
# "&" operator
set3 = set1 - set2
print("\difference using '&' operator")
print(set3)
set1에서 set2를 뺏기 떄문에 0,1,2 가 나오는 것이다.
set2에서 set1을 빼면 5,6,7,8 가 나옵니다.
Dicitonary
특징 1 : set과 마찬가지로 특정 순서대로 데이터를 리턴하지 않는다.
특징 2: Key의 값은 중복될 수 없다. 만약 중복이 된다면 나중에 에 입력된 값이 대체된다.
특징 3: set과 마찬가지로 순서가 없고 중복된 key는 허용돼지 않는다. key값이 bucket에 hash 저장
Dirctionary를 HashMap 또는 HashTable이라고도 한다
'Python' 카테고리의 다른 글
[Python] Unit Test (0) | 2020.07.26 |
---|---|
[Python] Bcrypt and Jwt (0) | 2020.07.14 |
[Python] 자료구조 Tuple,Array (0) | 2020.07.06 |
[Python] 크롤링-starbucks 음류수 종류 - csv (0) | 2020.07.03 |
[Python] 크롤링-billboard 차트 - csv (0) | 2020.07.02 |
댓글