Python集合基础

版权声明:版权归本人,仅供大家参考 https://blog.csdn.net/Dream____Fly/article/details/84450315

集合是无序的
集合中的元素是唯一的
集合可用来做关系测试
1.唯一性测试

List=[1,2,3,4,3,2,1,5,6,7,8]
List1=set(List)
print(List1)
	输出结果:{1, 2, 3, 4, 5, 6, 7, 8}

2.关系测试(取交集)

List1={7,6,5,4,3}
List2=[7,6,5,4]
print(List1.intersection(List2))
	输出结果:{4, 5, 6, 7}

3.取并集

List1={7,6,5,4,3}
List2=[7,6,5,4]
print(List1.union(List2))
	输出结果:{3, 4, 5, 6, 7}

4.取差集(去掉1中存在,而2中不存在的元素)

List1={7,6,5,4,3}
List2=[7,6,5,4]
print(List1.difference(List2))
	输出结果:{3}

5.判断父集

List1={7,6,5,4}
List2=[7,6,5,4,3]
print(List1.issuperset(List2))
	输出结果:False

6.取对称差集(会去掉1和2中都存在的元素)

List1={7,6,5,4}
List2=[7,6,5,4,3]
print(List1.symmetric_difference(List2))
	输出结果:{3}

猜你喜欢

转载自blog.csdn.net/Dream____Fly/article/details/84450315