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中國
集合爲空

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章