温馨提示×

python set怎么用

小亿
79
2024-01-18 16:41:08
栏目: 编程语言

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

  1. 创建一个空集合:
my_set = set()
  1. 创建一个包含元素的集合:
my_set = {1, 2, 3, 4, 5}
  1. 添加元素到集合中:
my_set.add(6)
  1. 从集合中删除元素:
my_set.remove(3)
  1. 检查集合中是否包含元素:
value = 4
if value in my_set:
    print("集合中包含该元素")
else:
    print("集合中不包含该元素")
  1. 遍历集合中的元素:
for item in my_set:
    print(item)
  1. 使用集合推导式创建一个集合:
my_set = {x for x in range(10) if x % 2 == 0}

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

0