在Python中,set()
函數(shù)用于創(chuàng)建一個新的集合。你可以通過將一個可迭代對象(如列表、元組或字符串)傳遞給set()
函數(shù)來創(chuàng)建一個集合。如果沒有提供任何參數(shù),set()
將創(chuàng)建一個空集合。
以下是使用set()
函數(shù)創(chuàng)建集合的示例:
# 使用列表創(chuàng)建集合
my_list = [1, 2, 3, 4, 5, 5, 6]
my_set = set(my_list)
print(my_set) # 輸出:{1, 2, 3, 4, 5, 6}
# 使用元組創(chuàng)建集合
my_tuple = (1, 2, 3, 4, 5, 5, 6)
my_set = set(my_tuple)
print(my_set) # 輸出:{1, 2, 3, 4, 5, 6}
# 使用字符串創(chuàng)建集合
my_string = "hello"
my_set = set(my_string)
print(my_set) # 輸出:{'h', 'e', 'l', 'o'}
# 創(chuàng)建空集合
empty_set = set()
print(empty_set) # 輸出:set()
請注意,集合中的元素是唯一的,因此在創(chuàng)建集合時,重復(fù)的元素將被自動刪除。