Python 中的 set 是一個無序的不重復元素集合,可以使用大括號 {}
或者內(nèi)置函數(shù) set()
來創(chuàng)建。這里有一些關(guān)于如何正確使用 Python 的 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}
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # 輸出:{1, 2, 3, 4}
my_set = {1, 2, 3, 4}
my_set.remove(4)
print(my_set) # 輸出:{1, 2, 3}
my_set = {1, 2, 3}
print(1 in my_set) # 輸出:True
print(4 in my_set) # 輸出:False
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
intersection = set_a.intersection(set_b)
print(intersection) # 輸出:{3, 4}
union = set_a.union(set_b)
print(union) # 輸出:{1, 2, 3, 4, 5, 6}
difference = set_a.difference(set_b)
print(difference) # 輸出:{1, 2}
symmetric_difference = set_a.symmetric_difference(set_b)
print(symmetric_difference) # 輸出:{1, 2, 5, 6}
my_set = {1, 2, 3, 4}
my_list = list(my_set)
print(my_list) # 輸出:[1, 2, 3, 4]
通過上述示例,你應該已經(jīng)了解了如何在 Python 中正確地使用 set 函數(shù)。記住,集合是一個無序的數(shù)據(jù)結(jié)構(gòu),所以它們不能被索引或排序。如果你需要這些功能,請考慮使用列表或元組。