溫馨提示×

python的set函數(shù)怎么使用

小億
88
2023-12-07 17:41:30
欄目: 編程語言

在Python中,set()函數(shù)用于創(chuàng)建一個集合(set)對象。集合是一個無序且不重復(fù)的集合,可以用于去除列表中的重復(fù)元素。

set()函數(shù)的語法如下:

set(iterable)

其中,iterable是一個可迭代對象(如列表、元組、字符串等)。

下面是一些使用set()函數(shù)的示例:

  1. 創(chuàng)建一個空集合:
empty_set = set()
  1. 創(chuàng)建一個包含多個元素的集合:
my_set = set([1, 2, 3, 4, 5])  # 使用列表作為參數(shù)
my_set = set((1, 2, 3, 4, 5))  # 使用元組作為參數(shù)
my_set = set("hello")          # 使用字符串作為參數(shù)
  1. 去除列表中的重復(fù)元素:
my_list = [1, 2, 1, 3, 4, 2, 5, 3]
unique_set = set(my_list)
  1. 添加元素到集合中:
my_set.add(6)
  1. 從集合中移除元素:
my_set.remove(3)
  1. 判斷元素是否在集合中:
if 3 in my_set:
    print("3 is in the set")

這些是set()函數(shù)的一些常見用法,你可以根據(jù)具體的需求來使用set()函數(shù)。

0