python set怎么用

Python中的set(集合)是一种无序且不重复的数据结构。可以使用set()函数或花括号{}创建一个集合。

创建一个空集合:

my_set = set()

创建一个包含元素的集合:

my_set = {1, 2, 3, 4, 5}

添加元素到集合中:

my_set.add(6)

从集合中删除元素:

my_set.remove(3)

检查集合中是否包含元素:

value = 4
if value in my_set:
    print("集合中包含该元素")
else:
    print("集合中不包含该元素")

遍历集合中的元素:

for item in my_set:
    print(item)

使用集合推导式创建一个集合:

my_set = {x for x in range(10) if x % 2 == 0}

注意:集合是无序的,因此无法通过索引访问集合中的元素。如果需要按照特定顺序处理集合中的元素,可以将集合转换为列表或使用sorted()函数进行排序。

阅读剩余
THE END