set
唯一性
無序性,不可索引
①{}括起一堆元素
變量可以是元組 列表 字符串 集合
例
去除掉列表中的重複元素
>>> num1 = {3,5,4,1,2,5,8,0,1,2,3}
>>> temp = []
>>> for each in num1:
if each not in temp:
temp.append(each)
>>> num1 = {3,5,4,1,2,5,8,0,1,2,3}
>>> num1 = list(set(num1))
>>> num1
[0, 1, 2, 3, 4, 5, 8]
①可以使用for把集合中的數據一個個讀取
3.對集合的操作
①add()
>>> num2 = {1,2,33,0}
>>> num2.add(5)
>>> num2
{0, 1, 2, 33, 5}
②remove()
>>> num3 = {3,8,0,1,2}
>>> num3.remove(8)
>>> num3
{0, 1, 2, 3}
frozenset()
>>> a = frozenset([2,5,3,1,0])
>>> a
frozenset({0, 1, 2, 3, 5})
>>> a.add(4)
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
a.add(4)
AttributeError: 'frozenset' object has no attribute 'add'
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Similarly to list comprehensions, set comprehensions are also supported:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}