# python基础知识-数据结构-set集合

XAMPP案例 95浏览

``````# 创建空集合
``````a_set = set()
``````
``````# 初始化一个集合
````b_set = {1, 2, 3, "a", "b"}````

``````a = {1, 2, 3, 4, 5}
``````
``````b = {4, 5, 6, 7, 8}
``````
``````# a中包含，且b中不包含的元素
``````print(a - b)
``````
``````# a或b 中的所有元素
``````print(a | b)
``````
``````# a和b中不同的元素
``````print(a ^ b)
``````
``````# a和b中相同的元素
``````print(a & b)
``````
``````
``````# 运行结果
``````{1, 2, 3}
``````{1, 2, 3, 4, 5, 6, 7, 8}
``````{1, 2, 3, 6, 7, 8}
``````{4, 5}
``````
````Process finished with exit code 0````

``````a = {1, 2, 3, 4, 5}
``````
``````# 判断元素是否在集合中，在就返回True，否则就返回False
``````if 1 in a:
``````    print(True)
``````else:
``````    print(False)
``````
``````# 定义一个列表
``````b = [1, 2, 3, 4, 5, 4, 3, 2, 6, 6, 6]
``````# 利用集合去重，再转为列表数据类型并打印
``````c = list(set(a))
``````print(c)
``````
``````
``````# 运行结果
``````True
``````[1, 2, 3, 4, 5]
``````
````Process finished with exit code 0````

``````# 使用列表推到创建集合
``````d = {x for x in '123456'}
``````print(d)
``````
``````
``````# 运行结果
``````{'6', '5', '2', '3', '4', '1'}
``````
````Process finished with exit code 0````