集合,
1.不同元素组成
2.无序
3.只能存放不可变类型,tuplestringint
# 1.不同元素组成,重复的不显示.
s = {1, 2, 3, 3, 3, 33}
print(s) # {33, 2, 3, 1}
print(type(s)) # <class 'set'>
for i in s:
print(i)
# 2.无序,多次执行,显示的顺序不同
s= {"hello", "world", "alex", "wupeiqi"}
print(s)
# 3.只能存放不可变类型
# s = {[1, 2], 2} # TypeError: unhashable type: 'list'
# 4. 另一种定义集合的方式,set, 只要里面是可迭代数据类型就可以,比如stringlist
s=set("hello")
print(s) # {'l', 'o', 'h', 'e'}
s=set(["alex", "alex", "hah"])
print(s) # {'hah', 'alex'}
###### 集合的内置方法 #######
# add
s = {1, 2, 3, 4, 5}
s.add("s")
s.add(3)
s.add('3')
print(s)
# clear清空
s.clear()
print(s) # set()
# copy
s = {1, 2, 3, 4, 5}
s1 = s.copy()
print(s1)
# pop 删除,集合是无序的,所以,随机删; remove/discard 指定删
s.pop()
print(s)
s.remove(3)
print(s)
# s.remove("noexist") # 删除不存在的,会报错
s.discard("5")
s.discard("noexist") # 删除不存在的,不会报错
class 集合的一些方法
"""
python_l = ["zhongguo", "riben", "meiguo"]
linux_l = ["zhongguo", "hanguo"]
# 统计两个列表都有的内容
python_linux_l = []
for i in python_l:
if i in linux_l:
print(i)
python_linux_l.append(i)
print(python_linux_l)
# 集合就能够实现交差并集,不然就需要使用上述丑陋的方式实现.
# 1.集合可以简单的进行去重.因为集合不会有重复的内容.(前提:不用考虑顺序)
# 2.求交集
python_l = ["zhongguo", "riben", "meiguo"]
linux_l = ["zhongguo", "hanguo"]
p_s = set(python_l)
l_s = set(linux_l)
print(p_s, l_s)
print(p_s.intersection(l_s)) # {'zhongguo'}
print(p_s&l_s) # {'zhongguo'}
# 3.求并集
print(p_s.union(l_s)) # {'zhongguo', 'hanguo', 'meiguo', 'riben'}
print(p_s|l_s) # {'zhongguo', 'hanguo', 'meiguo', 'riben'}
# 4. 求差集,存在于左边但不存在于右边.
print(p_s - l_s) # {'riben', 'meiguo'}
print(p_s.difference(l_s)) # {'meiguo', 'riben'}
# 同时更新值
p_s.difference_update(l_s)
print(p_s) # {'riben', 'meiguo'}
# 交叉补集, 并集然后去掉共同的部分.
python_l = ["zhongguo", "riben", "meiguo"]
linux_l = ["zhongguo", "hanguo"]
print(p_s.symmetric_difference(l_s)) # {'hanguo', 'meiguo', 'zhongguo', 'riben'}
print(p_s^l_s) # {'hanguo', 'meiguo', 'zhongguo', 'riben'}
# 判断是否交集为空
s1 = {1, 2}
s2 = {3, 4}
print(s1.isdisjoint(s2)) # True
# issubset s1<=s2 s1是s2的子集
s1 = {1, 2}
s2 = {1, 2, 3, 4}
print(s1.issubset(s2)) # True
print(s2.issubset(s1)) # False
# issuperset 判断是不是父集
print(s2.issuperset(s2)) # True
# update 求并集并更新到变量
s1 = {1, 2, 5}
s2 = {1, 2, 3, 4}
s1.update(s2)
s1.update([5, 6])
s1.update((8,9))
print(s1) # {1, 2, 3, 4, 5, 6, 8, 9}
"""
"""
集合是可变类型, frozenset可以创建不可修改集合
"""
s=frozenset() # 定义不可变集合
print(s) # frozenset()
names=["alex","alex","hah"]
names=list(set(names))
# 集合是可迭代类型
print(names) # ['hah', 'alex']