
目標
「データ構造」について理解する。
(pythonの)「集合」について概要を理解する。
(pythonの)「集合」について特徴を理解する。
「データ構造」の概要
「データ構造」とは
「データ構造」とは、0個以上の複数のデータを扱いやすく形式化したもので、pythonには「リスト」「タプル」「辞書」「集合」などがあります。
下の表はWikipediaより引用しています。
(出典)https://ja.wikipedia.org/wiki/%E3%83%87%E3%83%BC%E3%82%BF%E6%A7%8B%E9%80%A0

例えば、「スタック」だと複数のデータは積み上げられるようなイメージで保管されます。積み上げられるように保管されるので、最初に保管されたデータを取り出す場合は、後から追加されたデータも全て取り除いて取り出す必要があります。
このように、格納の方法と操作のルールがデータ構造には存在します。
(pythonの)「集合」の概要
(pythonの)「集合」とは
「集合」は要素の重複がなく順序を持たないオブジェクトの集まりです。「集合」
は「 {} 」を利用して表記します。(例 {’tomato’, ‘onion’, ‘cucumber’, ‘carrot’, ‘eggplant’, ‘potato’})
(pythonの)「集合」のイメージ
集合の要素には順序と重複がありません。袋に異なるオブジェクトが重複なく、詰められたイメージです。

集合の要素には順序がないため、次のふたつの集合は等価となります。
print({'tomato', 'onion', 'cucumber', 'carrot', 'eggplant', 'potato'} == {'carrot', 'potato', 'onion', 'cucumber', 'tomato', 'eggplant'})
実行結果


集合の要素には重複がないため、次のような集合を作成した場合、重複した値はひとつと見なされます。
print({'tomato', 'tomato', 'tomato', 'onion', 'onion', 'cucumber', 'carrot', 'carrot', 'eggplant', 'eggplant', 'eggplant', 'potato'})
実行結果

(pythonの)「集合」の表記方法
集合には「 {}(集合表記演算子)」を利用します。※辞書の「 {} 」は、同じ記号ですが、辞書表記演算子です。

(pythonの)「集合」の特徴
- 要素は順番がない。
- 要素は重複がない。
- 要素は追加・削除が可能(ミュータブル)。
- 要素は空(空集合)でもよい(表記は「set()」※「{}」は辞書の空)。
- 空集合の論理値は「False」。
- 内包表記による作成が可能。
今回は以上になります。

ブックマークのすすめ
「ほわほわぶろぐ」を常に検索するのが面倒だという方はブックマークをお勧めします。ブックマークの設定は別記事にて掲載しています。

