在Python中,set()
函數通常用于創建一個集合(set)
empty_set = set()
numbers = [1, 2, 3, 4, 5]
number_set = set(numbers)
print(number_set) # 輸出:{1, 2, 3, 4, 5}
duplicates = [1, 2, 2, 3, 4, 4, 5]
unique_elements = set(duplicates)
print(list(unique_elements)) # 輸出:[1, 2, 3, 4, 5]
set1 = {1, 2, 3}
set2 = {1, 2, 3}
print(set1 == set2) # 輸出:True
subset = {1, 2}
superset = {1, 2, 3, 4, 5}
print(subset.issubset(superset)) # 輸出:True
subset = {1, 2}
superset = {1, 2, 3, 4, 5}
print(superset.issuperset(subset)) # 輸出:True
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # 輸出:{1, 2, 3, 4, 5}
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection_set = set1.intersection(set2)
print(intersection_set) # 輸出:{2, 3}
set1 = {1, 2, 3}
set2 = {2, 3, 4}
difference_set = set1.difference(set2)
print(difference_set) # 輸出:{1}
set1 = {1, 2, 3}
set2 = {2, 3, 4}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # 輸出:{1, 4}