■ はじめに
https://dk521123.hatenablog.com/entry/2019/10/12/084943
https://dk521123.hatenablog.com/entry/2020/11/01/000000
https://dk521123.hatenablog.com/entry/2019/10/27/100014
https://dk521123.hatenablog.com/entry/2020/10/11/000000
の続き。 今回は、集合 Set について、メモする。
目次
【1】集合 ~ Set~ 【2】集合演算 1)積集合(共通部分、交わり) [補足] リストでは intersection はできない 【3】基本操作 【4】クローン
【1】集合 ~ Set~
* 重複排除 * set( ... ) を使う
例
results = set(["a1","b2","a1","c3"]) # ⇒ {'a1', 'b2', 'c3'}
【2】集合演算
1)積集合(共通部分、交わり)
fruits_1 = {"apple", "grape", "banana"} fruits_2 = {"melon", "grape", "water melon", "banana"} results = fruits_1.intersection(fruits_2) print(results) # {'banana', 'grape'}
[補足] リストでは intersection はできない
fruits_1 = ["apple", "grape", "banana"] fruits_2 = ["melon", "grape", "water melon", "banana"] results = fruits_1.intersection(fruits_2) # だと、エラーになる。 # AttributeError: 'list' object has no attribute 'intersection'
【3】基本操作
# 定義 sample_set = set() # 追加(add) sample_set.add('Hello') sample_set.add('World') sample_set.add('!!!') # {'!!!', 'Hello', 'World'} print(sample_set) # 削除(remove) sample_set.remove('World') # {'!!!', 'Hello'} print(sample_set) # 中に含まれているか if 'Hello' in sample_set: print('sample_set has Hello') # クリア(clear) sample_set.clear() # set() print(sample_set)
【4】クローン
「import copy」して使う。浅いコピーなら「set」で可能。 詳細は、以下の関連記事を参照のこと。
https://docs.python.org/ja/3/library/copy.html
サンプル
import copy # 浅いコピー1 sample_set = set(['Hello', 'World', '!!!']) cloned_set = copy.copy(sample_set) sample_set.add('Mike') # {'World', 'Mike', '!!!', 'Hello'} print(sample_set) # {'World', '!!!', 'Hello'} print(cloned_set) # 浅いコピー2 sample_set = set(['Hello', 'World', '!!!']) cloned_set = set(sample_set) sample_set.add('Mike') # {'World', 'Mike', '!!!', 'Hello'} print(sample_set) # {'World', '!!!', 'Hello'} print(cloned_set) # 深いコピー sample_set = set(['Hello', 'World', '!!!']) cloned_set = copy.deepcopy(sample_set) sample_set.add('Mike') # {'World', 'Mike', '!!!', 'Hello'} print(sample_set) # {'World', '!!!', 'Hello'} print(cloned_set)
参考文献
http://pythoncode.blog.fc2.com/blog-entry-109.html
参考文献
https://uxmilk.jp/14834
https://python.atelierkobato.com/set/
https://www.javadrive.jp/python/set/index6.html
関連記事
Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 基本編 / リスト ~
https://dk521123.hatenablog.com/entry/2019/10/12/084943
Python ~ 基本編 / リスト・あれこれ ~
https://dk521123.hatenablog.com/entry/2020/11/01/000000