Python–集合(set)

创建集合

# 创建集合
set1 = {10,20,30,40}
prin(set1)  # {10, 20, 30, 40}

# set()创建集合
set2 = set("hello")
print(set2)  # {'o', 'e', 'l', 'h'} 没有顺序

# set()创建空集合
set3 = set()
print(set3)  # set()
print(type(set3))  # set类型


集合增加数据

set1 = {10,20,30}
print(set1)  # {10, 'hello', 20, 30}


update()函数

set1 = {10,20,30}
set1.update([10,20,30,40,60,80])
print(set1)  # {40, 10, 80, 20, 60, 30}


集合删除数据

remove()函数

set1 = {10,20,30}
set1.remove(10)
print(set1)  # {20, 30}


set1 = {10,20,30}
print(set1)  # {20, 30}


pop()函数

set1 = {10,20,30}
print(set1.pop())  # 10


集合查找数据

in判断

set1 = {10,20,30}
print(10 in set1)  # True


not in判断

set1 = {10,20,30}
print(10 not in set1)  # False
print(0 not in set1)  # True


集合运算

交集

&：交集运算符号

set1 = {1,2,3}
set2 = {2,3,4}
a = set1 & set2
print(a)  # {2,3}


并集

|：并集运算符号

set1 = {1,2,3}
set2 = {2,3,4}
a = set1 | set2
print(a)  # {1, 2, 3, 4}


差集

-：差集运算符号

set1 = {1,2,3}
set2 = {2,3,4}
a = set1 - set2
print(a)  # {1}


对称差集

^：对称差集运算符号

a = {1,2,3,}
b = {2,3,4}
print(a^b)  # {1, 4}


10-25 1699

07-26 1万+
02-11 1595
12-18 501
02-13 6371
02-27 615
11-03 2261
06-23 480
08-06 2535
04-25 1079
08-14 4668
05-21 1万+
06-05 608
02-09 477
08-17 3259
08-16 1129