1. 程式人生 > >Python--16 集合 在我的世界裏,你就是唯一

Python--16 集合 在我的世界裏,你就是唯一

line spa support 得到 num strong [] style 可變集合

  >>> num = {}
  >>> type(num)
  <class ‘dict‘>
  >>> num2 = {1,2,3,4,5}
  >>> type(num2)
  <class ‘set‘>

  >>> num2
  {1, 2, 3, 4, 5}
  >>> num2[1]
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: ‘set‘ object does not support indexing

如何創建一個集合  

 一種時直接把一堆元素用花括號括起來

 一種是使用set()工廠函數

  set()得到的數據是無序的

  >>> set1 = set([1,2,3,4,5,6,6])
  >>> set1
  {1, 2, 3, 4, 5, 6}

 去重復元素

  >>> set1 = set([1,2,3,4,5,6,6])
  >>> set1
  {1, 2, 3, 4, 5, 6}
  >>> num1 = [1,2,3,4,5,6,4,2,1,0]
  >>> temp = []


  >>> for each in num1:
    ... if each not in temp:
    ... temp.append(each)
    ...
  >>> temp
  [1, 2, 3, 4, 5, 6, 0]

  >>> num1 = list(set(num1))
  >>> num1
  [0, 1, 2, 3, 4, 5, 6]

 in not in

  >>> 1 in num1
  True
  >>> ‘1‘ in num1
  False

  add() remove()

  >>> num2
  {1, 2, 3, 4, 5}
  >>> num2.add(‘12‘)
  >>> num2
  {1, 2, 3, 4, 5, ‘12‘}
  >>> num.remove(5)  
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AttributeError: ‘dict‘ object has no attribute ‘remove‘
  >>> num2.remove(5)
  >>> num2
  {1, 2, 3, 4, ‘12‘}

 frozen:冰凍的,凍結的 不可變集合

  >>> num3 = frozenset([1,2,3,4,5])
  >>> num3.add(6)
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AttributeError: ‘frozenset‘ object has no attribute ‘add‘

Python--16 集合 在我的世界裏,你就是唯一