파이썬에는 크게 set, dictionary, list, tuple 4가지 자료구조가 있다. 차이점에 대해 알아보자!
👉 중복된 값은 저장이 안된다.
#생성
set1 = {1, 2, 3, 1}
print(set1) #{1,2,3}
set2 = set([1, 2, 3, 1])
print(set2) #{1,2,3}
#추가
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) #{1,2,3,4}
#삭제
my_set = {1, 2, 3}
my_set.remove(3)
print(my_set) #{1,2}
👉 in 사용하여 알아보기
my_set = {1, 2, 3}
if 1 in my_set:
print("1 is in the set")
# 1 is in the set
if 4 not in my_set:
print("4 is not in the set")
# 4 is not in the set
👉교집합은 "&" 합집합은 "|"을 이용한다.
# Intersection(교집합)
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
print(set1 & set2)
# {4, 5, 6}
print(set1.intersection(set2))
# {4, 5, 6}
#Union(합집합)
print(set1 | set2)
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set1.union(set2))
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
#읽기
#추가
dict = {1:"one","two":2}
dict[3]="three"
print(dict)
#{1: 'new one', 'two': 2, 3 :'three' }
#수정
my_dict = { "one": 1, 2: "two", 3 : "three" }
my_dict["four"] = 4
print(my_dict)
# {'one': 1, 2: 'two', 3: 'three', 'four': 4
#삭제
my_dict = { "one": 1, 2: "two", 3 : "three" }
del my_dict["one"]
print(my_dict)
#{2: 'two', 3: 'three'}