在Python中,set()
函數(shù)用于創(chuàng)建一個集合(set)。集合是一個無序的不重復(fù)元素序列。這里有一些關(guān)于如何使用 set()
函數(shù)的實際案例:
empty_set = set()
print(empty_set) # 輸出:set()
my_list = [1, 2, 3, 4, 4, 5, 6, 6]
my_set = set(my_list)
print(my_set) # 輸出:{1, 2, 3, 4, 5, 6},注意重復(fù)的元素被去除了
my_string = "hello world"
my_set = set(my_string)
print(my_set) # 輸出:{'h', 'e', 'l', 'o', ' ', 'w', 'r', 'd'},注意重復(fù)的字符被去除了
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 并集
union_set = set1.union(set2)
print(union_set) # 輸出:{1, 2, 3, 4, 5, 6, 7, 8}
# 交集
intersection_set = set1.intersection(set2)
print(intersection_set) # 輸出:{4, 5}
# 差集
difference_set = set1.difference(set2)
print(difference_set) # 輸出:{1, 2, 3}
# 對稱差集
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # 輸出:{1, 2, 3, 6, 7, 8}
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
# 判斷子集
is_subset = set1.issubset(set2)
print(is_subset) # 輸出:True
# 判斷超集
is_superset = set2.issuperset(set1)
print(is_superset) # 輸出:True
這些實際案例展示了如何在Python中使用 set()
函數(shù)以及集合的基本操作。