Python 集合处理的10个常用方法

S.add(x) 如果x不在集合S中,将x增加到S

S.discard(x) 移除S中元素x,如果x不在集合S中,不报错

S.remove(x) 移除S中元素x,如果x不在集合S中,产生KeyError异常

S.clear() 移除S中所有元素

S.pop() 随机返回S的一个元素,更新S,若S为空产生KeyError异常

S.copy() 返回集合S的一个副本

len(S) 返回集合S的元素个数

x in S 判断S中元素x,x在集合S中,返回True,否则返回False

x not in S 判断S中元素x,x不在集合S中,返回True,否则返回False

set(x) 将其他类型变量x转变为集合类型

D = set('b12')
D.add("CC")
print(D)
X = {'213', 'go', 'php'}
X.discard('php')
print(X)

try:
    V = set('as')
    V.remove('a')
except:
    print('V集合不纯在as')
else:
    print(V)
finally:
    print('继续执行')

输出:

{'b', '1', 'CC', '2'}
{'213', 'go'}
{'s'}
继续执行

S = {'sa', 4654,'sd'}
S.clear()
print(S)
E = {'中国', 666, 'ch'}
print(E.pop())

输出:

set()
中国

S = {'123',99,'中国'}
print(len(S))

print(99 in S)
print('中国' not in S)

s = "我爱你中国"
d = ['as', 132,'lopve']
y = (365,"中国",'Python')
print(set(s))
print(set(d))
print(set(y))


输出:

3
True
False
{'中', '你', '我', '爱', '国'}
{132, 'lopve', 'as'}
{'Python', 365, '中国'}

A = {'E', '中国', 123}
try:
    while True:
        print(A.pop(), end="")#S.pop() 随机返回S的一个元素,更新S,若S为空产生KeyError异常
except:
    print('\n集合为空')

输出:

123E中国
集合为空

你可能感兴趣的:(Python)