如何在Python中創(chuàng)建set集合

小樊
83
2024-09-06 12:59:22
欄目: 編程語言

在Python中,您可以使用大括號(hào) {} 或者內(nèi)置的 set() 函數(shù)來創(chuàng)建一個(gè)集合(set)

方法1:使用大括號(hào) {}

my_set = {1, 2, 3, 4, 5}
print(my_set)  # 輸出:{1, 2, 3, 4, 5}

方法2:使用 set() 函數(shù)

my_set = set([1, 2, 3, 4, 5])
print(my_set)  # 輸出:{1, 2, 3, 4, 5}

注意:空的大括號(hào) {} 是用來創(chuàng)建字典(dictionary)的,而不是集合(set)。要?jiǎng)?chuàng)建一個(gè)空集合,請(qǐng)使用 set() 函數(shù),如下所示:

empty_set = set()
print(empty_set)  # 輸出:set()

0