标签:list ted 数学 清空 == 多重 rand 个数 opera
# 集合的定义 s = set() print(type(s)) print(s) print("*"*30) # 此时,大括号内一定要有值,否则定义出的是一个dict s = {} print(type(s)) print(s) print("*"*30) s = {1,2,3,4,5} print(type(s)) print(s)
<class ‘set‘> set() ****************************** <class ‘dict‘> {} ****************************** <class ‘set‘> {1, 2, 3, 4, 5}
# 如果只是用大括号定义,则定义的是一个dict类型 d = {} print(type(d)) print(d)
<class ‘dict‘> {}
# 成员检测 # in not in s = {4,5,"i", "love", "python"} print(s) if "love" in s: print("爱呀") if "haha" not in s: print("挨个锤子")
{‘love‘, 4, 5, ‘python‘, ‘i‘} 爱呀 挨个锤子
# for 循环 s = {4,5,"i", "love", "python"} for i in s: print(i, end=" ") # 得到的结果就是随机的
love 4 5 python i
# 带有元组的集合遍历 s = {(1,2,3), ("i", "love", "python"), (4,5,6)} for k,m,n in s: print(k, "--", m, "--", n) for k in s: print(k)
i -- love -- python 4 -- 5 -- 6 1 -- 2 -- 3 (‘i‘, ‘love‘, ‘python‘) (4, 5, 6) (1, 2, 3)
# 普通集合的内涵 # 以下的集合 s = {1,2,3,5,6,2,3,5,1,2,3,2,2,8,4,6,2} print(s) # 普通集合的内涵 ss = {i for i in s if i % 2==0} print(ss)
{1, 2, 3, 4, 5, 6, 8} {8, 2, 4, 6}
# 带有条件的集合内涵 ss = {i for i in s if i % 2==0} print(ss)
{8, 2, 4, 6}
# 多重循环的集合内涵 s1 = {1,2,3,4} s2 = {"i","love","python"} s = {m*n for m in s2 for n in s1} print(s)
{‘love‘, ‘lovelovelove‘, ‘iiii‘, ‘pythonpythonpythonpython‘, ‘lovelovelovelove‘, ‘ii‘, ‘iii‘, ‘pythonpython‘, ‘python‘, ‘lovelove‘, ‘pythonpythonpython‘, ‘i‘}
# len, max, min:跟其他基本函数一致 s = {43,23,56,223,4,2,1222,4,323,1} print(len(s)) print( max(s)) print(min(s))
9 1222 1
# set:生成一个集合 l = [1,2,3,4,3,23,1,2,3,4] s = set(l) print(s)
{1, 2, 3, 4, 23}
# add:向集合内添加元素 s = {1} s.add(2) print(s)
{1, 2}
# clear s = {1,5,6,8} print(s) print(id(s)) s.clear() print(s) print(id(s)) # 结果表明clear函数是原地清空数据
{8, 1, 5, 6} 139677107966472 set() 139677107966472
# copy:拷贝 # remove:移除制定的值,直接改变原有值,如果要删除的值不存在,报错 # discard:移除集合中指定的值,跟remvoe一样,但是如果要删除的话,不报错 s = {23,3,4,5,1,2,3} s.remove(4) print(s) s.discard(1) print(s) print("*" * 20) s.discard(1100) print(s) s.remove(1100) print(s) # 为啥remove不存在的值会报keyerror 思考?
# pop 随机移除一个元素 s = {1,5,2,3,5,6} d = s.pop() print(s) print(d)
{2, 3, 5, 6} 1
# 集合函数 # intersection();交际 # difference():差集 # union:并集 # issubset: 检查一个集合是否为另一个子集 # issuperset: 检查一个集合是否为另一个超集 s1 = {1,2,3,4,5,6} s2 = {5,6,7,8,9} s_1 = s1.intersection(s2) print(s_1) s_2 = s1.difference(s2) print(s_2) s_3 = s1.issubset(s2) print(s_3)
{5, 6} {1, 2, 3, 4} False
# 集合数学操作 s1 = {1,2,3,4,5,6} s2 = {5,6,7,8,9} s_1 = s1 - s2 print(s_1) s_2 = s1 + s2 print(s_2)
# 此处不支持数学操作中的+操作
标签:list ted 数学 清空 == 多重 rand 个数 opera
原文地址:https://www.cnblogs.com/cswzp/p/10000328.html