06集合

集合
set
唯一性
無序性,不可索引
1.集合的創建
①{}括起一堆元素
②使用工廠函數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]
2.訪問集合中的值
①可以使用for把集合中的數據一個個讀取
②通過in 和 not in 判斷一個元素是否在集合中已經存在

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}

4.不可變集合
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'

5.集合的數學運算   &|^   交併補
>>> 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'}


發佈了41 篇原創文章 · 獲贊 1 · 訪問量 3365
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章