セット(順序なしデータと最適化された論理演算)

Python のデータ型

Jason Myers

Instructor

セット

  • 重複なし
  • 無順序
  • 変更可
  • 数学の集合論をPythonで実装
Python のデータ型

セットの作成

  • セットはリストから作成します
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() は要素を1つ追加します
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() は他のセットやリストを結合します
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...