集合

# 集合 { } 由不同元素(会去重)组成的集合,无序的
# 可添加删除,不可修改(如果使用 s=frozenset('hello'),则不可变)
# 只能存放不可变类型(数字,字符串,元组)

# 定义方式1
s = {1, 2, 3, 'hello', (0, 8)}
# 定义方式2(使用可迭代对象)
s = set(['hello', 'world'])

# for循环
for i in s:
    print(i)

# in 操作
print(2 in s)
print(2 not in s)

# 添加一个值
s.add('ok')

# 清空
s.clear()

# copy,浅拷贝
s1 = s.copy()

# 随机删除
s.pop()

# 指定删除, 不存在则报错
s.remove('ok')

# 指定删除, 不存在不会报错
s.discard('ok')




# 集合关系运算
python_l = ['lcg', 'szw', 'zjw']
linux_l = ['lcg', 'szw', 'sb']
p_s = set(python_l)
l_s = set(linux_l)
# 交集
print(p_s.intersection(l_s))   # 或者使用&
print(p_s & l_s)
# intersection_update 参考差集的difference_update

# 并集
print(p_s.union(l_s))  # 或者使用|
print(p_s | l_s)
# update 参考差集的difference_update

# 差集 (存在于左边的集合,不存在于右边的集合)
print(p_s.difference(l_s))  # 或者使用-
print(p_s - l_s)
# 求完差集后将结果更新至左边的集合
p_s.difference_update(l_s)
print(p_s)  # 等同于
p_s = p_s - l_s

# 交叉补集 (将两个集合合在一起减去它们共有的部分)
print(p_s.symmetric_difference(l_s))  # 或者使用^
print(p_s ^ l_s)
# symmetric_difference_update 参考差集的difference_update

# 判断两个集合是否有交集 没有返回True 有返回False
print(p_s.isdisjoint(l_s))

# 判断左边的集合是否是右边集合的子集 是返回True 不是返回False
print(p_s.issubset(l_s))  # 或者使用<=
print(p_s <= l_s)

# 判断左边的集合是否是右边集合的父集 是返回True 不是返回False
print(p_s >= l_s)  # 或者使用>=

 

posted @ 2018-08-02 22:19  四十不惑的编程之路  阅读(116)  评论(0编辑  收藏  举报