集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。
# {}符号
set_ = set() # 创建集合
set_.add("test") # 添加元素
set_1 = {2, 45, 6, 789, 45} # 集合
print(set_, type(set_)) # {'test'} <class 'set'>
print(set_1, type(set_1)) # {2, 789, 45, 6} <class 'set'>
# add添加 不能添加非哈希的对象 set本身也是非哈希的
set_ = set()
set_.add("test") # 添加
print(set_) # {'test'}
set_.add(123) # {123, 'test'}
print(set_)
set_.add((1, 2, 3))
print(set_) # {123, 'test', (1, 2, 3)}
# set_.add({"name": "Tom"}) # TypeError: unhashable type: 'dict'
# update 更新
set_2 = {12, 45}
set_.update(set_2) # 将set_2更新到set_中
print(set_) # {45, 123, 'test', 12, (1, 2, 3)}
set_ = {45, 123, 'test', 12, (1, 2, 3)}
#
# remove
set_.remove("test")
print(set_) # {12, 45, (1, 2, 3), 123}
set_.remove((1, 2, 3))
print(set_) # {12, 45, 123}
# pop
set_ = {45, 123, 'test', 12, (1, 2, 3)}
# ret = set_.pop() # 是随机删除的 集合是无序的
# print(ret) # ??
print(set_) # {45, (1, 2, 3), 'test', 123}
# remove 找不到报错
set_.remove(45) # {12, 'test', (1, 2, 3), 123}
print(set_)
# set_.remove("aaa") # KeyError: 'aaa'
# clear
set_.clear()
print(set_) # set()
# del
# del set_[12] 'set' object doesn't support item deletion
del set_
print(set_) # NameError: name 'set_' is not defined
set_ = {45, 123, 'test', 12, (1, 2, 3)}
for set_data in set_:
print(set_data, end=" ") # 12 45 (1, 2, 3) test 123
set1 = {1, 2, 3, 7, 8}
set2 = {2, 3, 6, 9}
print(set1 & set2) # 交集 {2, 3}
print(set1 | set2) # 并集 {1, 2, 3, 6, 7, 8, 9}
print(set1 ^ set2) # 反交集{1, 6, 7, 8, 9}
print(set1 - set2) # 差集 {8, 1, 7}
print(set2 - set1) # 差集 {9, 6}
print(set1<set2) # 子集与超集 False
print(set1.intersection(set2)) # 交集 {2, 3}
print(set1.union(set2)) # 并集 {1, 2, 3, 6, 7, 8, 9}
print(set1.symmetric_difference(set2)) # 反交集{1, 6, 7, 8, 9}
print(set1.difference(set2)) # 差集 {8, 1, 7}
print(set2.difference(set1)) # 差集 {9, 6}
print(set1.issubset(set2)) # 子集与超集 False
# frozenset不可变集合,让集合变成不可变类型。
s = frozenset('test')
print(s, type(s)) # frozenset({'t', 's', 'e'}) <class 'frozenset'>
原文:https://www.cnblogs.com/yangchangjie150330/p/10485534.html