集合(無序資料,優化的邏輯運算)

Python 的資料型別

Jason Myers

Instructor

集合

  • 元素唯一
  • 無序
  • 可變動
  • Python 對數學集合論的實作
Python 的資料型別

建立集合

  • 由 list 建立集合
cookies_eaten_today = ['chocolate chip', 'peanut butter', 
   ...: 'chocolate chip', 'oatmeal cream', 'chocolate chip']

types_of_cookies_eaten = set(cookies_eaten_today)
print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter'])
Python 的資料型別

修改集合

  • .add() 新增單一元素
types_of_cookies_eaten.add('biscotti')

types_of_cookies_eaten.add('chocolate chip')

print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter', 'biscotti'])
Python 的資料型別

更新集合

  • .update() 併入另一個 set 或 list
cookies_hugo_ate = ['chocolate chip', 'anzac']

types_of_cookies_eaten.update(cookies_hugo_ate)

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream',  'peanut butter', 'biscotti'])
Python 的資料型別

從集合移除資料

  • .discard() 依值安全移除元素
  • .pop() 移除並回傳任意元素(空集合會拋出 KeyError)
types_of_cookies_eaten.discard('biscotti')

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
types_of_cookies_eaten.pop()
types_of_cookies_eaten.pop()
'chocolate chip'
'anzac'
Python 的資料型別

集合運算-相同處

  • .union() 傳回所有名稱的集合(「or」)
  • .intersection() 找出重疊資料(「and」)
cookies_jason_ate = set(['chocolate chip', 'oatmeal cream',
'peanut butter'])
cookies_hugo_ate = set(['chocolate chip', 'anzac'])

cookies_jason_ate.union(cookies_hugo_ate)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
cookies_jason_ate.intersection(cookies_hugo_ate)
set(['chocolate chip'])
Python 的資料型別

集合運算-差異

  • .difference() 找出目標集合中存在、但引數中沒有的資料(「-」)
  • 重點在目標!
cookies_jason_ate.difference(cookies_hugo_ate)
set(['oatmeal cream', 'peanut butter'])
cookies_hugo_ate.difference(cookies_jason_ate)
set(['anzac'])
Python 的資料型別

一起來練習吧!

Python 的資料型別

Preparing Video For Download...