Python 中set集合类型(去重、成员运算)
集合类型的作用:去重以及成员运算
# 第一种、创建集合,使用花括号{},打印默认去重 one_set = {10, 20, 33, 10, 22, 33, 20} print(one_set) # 第二种、创建集合,使用花括号set({值}),打印默认去重 two_set = set([10, 10, 20, 44, 10, 66, 44, 20]) print(two_set) # 创建空集合 # 不能使用{}来创建空集合,默认创建的是空字典 empty_set = set() print(type(empty_set)) 执行结果: {33, 10, 20, 22} {10, 20, 66, 44} <class 'set'>
示例:
one_set1 = set([10, 20, 33, 10, 22, 33, 20]) two_set1 = set({10, 10, 20, 44, 10, 66, 44, 20}) # 求交集,去重之后公共元素, & 及 .intersection(译:因特塞克神) result_set1 = one_set1 & two_set1 result_set11 = one_set1.intersection(two_set1) print(result_set1) # 结果:{10, 20} print(result_set11) # 结果:{10, 20} # 求并集,合并在一起, result_set2 = one_set1 | two_set1 result_set22 = one_set1.union(two_set1) # (译:有你恩呢) print(result_set2) # 结果:{33, 66, 10, 44, 20, 22} print(result_set22) # 结果:{33, 66, 10, 44, 20, 22} # 求差集,只在其中一个,不在另一个 result_set3 = one_set1 - two_set1 result_set33 = one_set1.difference(two_set1) # (译:地府云词) print(result_set3) # 结果:{33, 22} print(result_set33) # 结果:{33, 22} # 对称差集,要么在A,要么在B,没有公共元素 result_set4 = one_set1 ^ two_set1 result_set44 = one_set1.symmetric_difference(two_set1) print(result_set4) # 结果:{33, 66, 44, 22} print(result_set44) # 结果:{33, 66, 44, 22} # 如何判断一个元素是否在其中 # 判断33是否在one_set1 a = 33 in one_set1
*******请大家尊重原创,如要转载,请注明出处:转载自:https://www.cnblogs.com/shouhu/,谢谢!!*******
本文仅供参考;如果这篇文件对你有所帮助,麻烦动动发财的小手,推荐一波支持下万分感谢
*******请大家尊重原创,如要转载,请注明出处:作者:守护@往昔;转载自:https://www.cnblogs.com/shouhu/,谢谢!!*******