セット 編集

セット(set; 集合)は、一意で不変のオブジェクトの、順不同の有限集合を表します。 そのため、どのような添え字でもインデックスを付けることはできません。 しかし、反復処理することは可能で、組込み関数len() は、セット内のアイテムの数を返します。 集合の一般的な用途は、高速なメンバーシップテスト、シーケンスからの重複の除去、および交叉、和集合、差集合、対称差などの数学的操作の計算です[1]

コンストラクターとリテラルと内包表記 編集

コンストラクターとリテラル
print(f'''\
{ set()=}
{ set([10,20,30,10])=}
{ set(range(10))=}
{ {10, "ABC", 30}=}
{ {i for i in range(10)}=}
{ {(1,"one"), (2,"two"),(3,"three"),(1,"one")}=}
{ {
    (1,"壱"),
    (2,"弐"),
    (3,"参"),
    (1,"壱"),
    }=}
{ {1,6,2,4,2,6,2,3}=}\
''')
実行結果
 set()=set()
 set([10,20,30,10])={10, 20, 30}
 set(range(10))={0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
 {10, "ABC", 30}={'ABC', 10, 30}
 {i for i in range(10)}={0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
 {(1,"one"), (2,"two"),(3,"three"),(1,"one")}={(3, 'three'), (2, 'two'), (1, 'one')}
 {
    (1,"壱"),
    (2,"弐"),
    (3,"参"),
    (1,"壱"),
    }={(3, '参'), (1, '壱'), (2, '弐')}
 {1,6,2,4,2,6,2,3}={1, 2, 3, 4, 6}
空のセットは、コンストラクターである組込み関数setを引数無しで呼び出し生成します({}は辞書になります)。
コンストラクターにイテレータブルオブジェクトを渡すと、イテレータブルオブジェクトの要素の集合をかえします(この場合も重複排除が働きます)。
セットリテラルは、要素をカンマ , で区切り全体を波括弧 { } で囲みます。
セットにも内包表記があり、{ 式 for 変数 in イテレーター }の形式です。

セットと演算子 編集

セットと演算子
s1 = {10, "ABC", 30}

print(
    f"""\
{s1=}
{s1 - {10, 20, 30}=}
{s1 | {2, 3, 4}=}
{s1 & {10, 20, 30}=}
{s1 ^ {10, 20, 30}=}
{s1 == {10 ,"ABC" ,30}=}
{s1 != {10 ,"ABC" ,30}=}
{s1 > {10 ,"ABC" ,30}=}
{s1 < {10 ,"ABC" ,30}=}
"""
)
実行結果
s1={10, 'ABC', 30}
s1 - {10, 20, 30}={'ABC'}
s1 | {2, 3, 4}={2, 3, 'ABC', 4, 10, 30}
s1 & {10, 20, 30}={10, 30}
s1 ^ {10, 20, 30}={20, 'ABC'}
s1 == {10 ,"ABC" ,30}=True
s1 != {10 ,"ABC" ,30}=False
s1 > {10 ,"ABC" ,30}=False
s1 < {10 ,"ABC" ,30}=False
セット同士の減算は、差集合を返します。
セット同士の論理和( + や or ではなく | )は、和集合を返します。
セット同士の論理積( * や and ではなく & )は、交叉を返します。
セット同士の排他的論理和( xor ではなく ^ )は、対称差を返します。
セット同士は、比較や大小判別ができます。

演算子形式とメソッド形式 編集

演算子形式とメソッド形式
s = {i for i in range(10)}
e = {i for i in range(10) if i % 2 == 0}
o = {i for i in range(10) if i % 2 != 0}

print(f"""\
{ s=}
{ e=}
{ o=}
{ len(s)=} # 集合の濃度
{ 3 in s=} # 3は集合sに含まれるか
{ 10 not in s=} # 10は集合sに含まれ**ない**か
{ e | o == s =} # 0..9の偶数と0..9の奇数の和集合は、0..9に等しいか?
{ e.union(o) == s =} # 0..9の偶数と0..9の奇数の和集合は、0..9に等しいか?
{ {0,3,6,9}.union({1,4,7}, {2,5,8}) == s =} # unionは2つ以上引数を持てる
{ s - e == o =} # 0..9と0..9の偶数の差集合は、0..9の奇数に等しいか?
{ s.difference(e) == o =} # 0..9と0..9の偶数の差集合は、0..9の奇数に等しいか?
{ s.difference(e,o) =} # differenceは2つ以上引数を持てる
{ e ^ o == s =} # 0..9の偶数と0..9の奇数の和集合は、0..9に等しいか?
{ e.symmetric_difference(o) == s =} # 0..9の偶数と0..9の奇数の和集合は、0..9に等しいか?
{ {1,3,5}.isdisjoint({2,4,6})=} # 共通要素がない
{ {1,2,3}.isdisjoint({2,4,6})=} # 要素2が共通
{ e.issubset(s)=} # eはsの部分集合
{ e <= s=} # eはsの部分集合?
{ e < s=} # eはsの真部分集合?
{ o < s=} # oはsの真部分集合?
{ o | e < s=} # oとeの和集合はsの真部分集合?\
""")
実行結果
s={0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
 e={0, 2, 4, 6, 8}
 o={1, 3, 5, 7, 9}
 len(s)=10 # 集合の濃度
 3 in s=True # 3は集合sに含まれるか
 10 not in s=True # 10は集合sに含まれ**ない**か
 e | o == s =True # 0..9の偶数と0..9の奇数の和集合は、0..9に等しいか?
 e.union(o) == s =True # 0..9の偶数と0..9の奇数の和集合は、0..9に等しいか?
 {0,3,6,9}.union({1,4,7}, {2,5,8}) == s =True # unionは2つ以上引数を持てる
 s - e == o =True # 0..9と0..9の偶数の差集合は、0..9の奇数に等しいか?
 s.difference(e) == o =True # 0..9と0..9の偶数の差集合は、0..9の奇数に等しいか?
 s.difference(e,o) =set() # differenceは2つ以上引数を持てる
 e ^ o == s =True # 0..9の偶数と0..9の奇数の和集合は、0..9に等しいか?
 e.symmetric_difference(o) == s =True # 0..9の偶数と0..9の奇数の和集合は、0..9に等しいか?
 {1,3,5}.isdisjoint({2,4,6})=True # 共通要素がない
 {1,2,3}.isdisjoint({2,4,6})=False # 要素2が共通
 e.issubset(s)=True # eはsの部分集合
 e <= s=True # eはsの部分集合?
 e < s=True # eはsの真部分集合?
 o < s=True # oはsの真部分集合?
 o | e < s=False # oとeの和集合はsの真部分集合?

メソッド keys(), values(), items()の返すオブジェクト 編集

keys(), values(), items()の返すオブジェクトは、それぞれキー、値、キーと値のペアーのタプルのイテレータブルですが、関数から返った値は辞書とその後も結びついています(これらのオブジェクトをセット・ビュー オブジェクトと呼びます)。 リストのように静的なオブジェクトではありません。

メソッド keys(), values(), items()の返す値
a = { 1:"one",2:"two", 3:"three"}
k = a.keys()
v = a.values()
i = a.items()
print(f"{a=}\n{k=}\n{v=}\n{i=}\n")

a[0] = "zero"

print(f"{a=}\n{k=}\n{v=}\n{i=}\n")

del a[1]

print(f"{a=}\n{k=}\n{v=}\n{i=}\n")
実行結果
a={1: 'one', 2: 'two', 3: 'three'}
k=dict_keys([1, 2, 3])
v=dict_values(['one', 'two', 'three'])
i=dict_items([(1, 'one'), (2, 'two'), (3, 'three')])

a={1: 'one', 2: 'two', 3: 'three', 0: 'zero'}
k=dict_keys([1, 2, 3, 0])
v=dict_values(['one', 'two', 'three', 'zero'])
i=dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (0, 'zero')])

a={2: 'two', 3: 'three', 0: 'zero'}
k=dict_keys([2, 3, 0])
v=dict_values(['two', 'three', 'zero'])
i=dict_items([(2, 'two'), (3, 'three'), (0, 'zero')])

破壊的メソッド 編集

破壊的メソッドは、レシーバーであるセットオブジェクト自体を変更するメソッドです。

破壊的メソッド
a = {1,2,3}     
print(f"a = {1,2,3}\n{ a=}")
a.add(4)        
print(f"a.add(4)\n {a=}")
a.remove(2)     
print(f"a.remove(2)\n {a=}")
try:
    a.remove(0) 
    print(f"a.remove(0)\n {a=}")
except KeyError as e:
    print(type(e).__name__, e)
a.discard(0)    
print(f"a.discard(0)\n {a=}")
b = a.copy()    
print(f"b = a.copy()\n {b=}")
try:
    while True:    
        print(f"{a.pop()}", end=", ")
except KeyError as e:
    print(type(e).__name__, e)
print(f" {a=}, {b=}")
b.clear()       
print(f"b.clear()\n {b=}")
実行結果
a = (1, 2, 3)
 a={1, 2, 3}
a.add(4)
 a={1, 2, 3, 4}
a.remove(2)
 a={1, 3, 4}
KeyError 0
a.discard(0)
 a={1, 3, 4}
b = a.copy()
 b={1, 3, 4}
1, 3, 4, KeyError 'pop from an empty set'
 a=set(), b={1, 3, 4}
b.clear()
 b=set()

セットのフィールド一覧 編集

セットのフィールド一覧
obj = set()
for i in dir(obj):
    print(i, 
        eval(f"type({obj}.{i}).__name__"),
        eval(f"({obj}.{i}).__doc__"),
        sep=", "
        )
実行結果
__and__, method-wrapper, Return self&value.
__class__, type, set() -> new empty set object
set(iterable) -> new set object

Build an unordered collection of unique elements.
__contains__, builtin_function_or_method, x.__contains__(y) <==> y in x.
__delattr__, method-wrapper, Implement delattr(self, name).
__dir__, builtin_function_or_method, Default dir() implementation.
__doc__, str, str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
__eq__, method-wrapper, Return self==value.
__format__, builtin_function_or_method, Default object formatter.
__ge__, method-wrapper, Return self>=value.
__getattribute__, method-wrapper, Return getattr(self, name).
__gt__, method-wrapper, Return self>value.
__hash__, NoneType, None
__iand__, method-wrapper, Return self&=value.
__init__, method-wrapper, Initialize self.  See help(type(self)) for accurate signature.
__init_subclass__, builtin_function_or_method, This method is called when a class is subclassed.

The default implementation does nothing. It may be
overridden to extend subclasses.

__ior__, method-wrapper, Return self|=value.
__isub__, method-wrapper, Return self-=value.
__iter__, method-wrapper, Implement iter(self).
__ixor__, method-wrapper, Return self^=value.
__le__, method-wrapper, Return self<=value.
__len__, method-wrapper, Return len(self).
__lt__, method-wrapper, Return self<value.
__ne__, method-wrapper, Return self!=value.
__new__, builtin_function_or_method, Create and return a new object.  See help(type) for accurate signature.
__or__, method-wrapper, Return self|value.
__rand__, method-wrapper, Return value&self.
__reduce__, builtin_function_or_method, Return state information for pickling.
__reduce_ex__, builtin_function_or_method, Helper for pickle.
__repr__, method-wrapper, Return repr(self).
__ror__, method-wrapper, Return value|self.
__rsub__, method-wrapper, Return value-self.
__rxor__, method-wrapper, Return value^self.
__setattr__, method-wrapper, Implement setattr(self, name, value).
__sizeof__, builtin_function_or_method, S.__sizeof__() -> size of S in memory, in bytes
__str__, method-wrapper, Return str(self).
__sub__, method-wrapper, Return self-value.
__subclasshook__, builtin_function_or_method, Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__().
It should return True, False or NotImplemented.  If it returns
NotImplemented, the normal algorithm is used.  Otherwise, it
overrides the normal algorithm (and the outcome is cached).

__xor__, method-wrapper, Return self^value.
add, builtin_function_or_method, Add an element to a set.

This has no effect if the element is already present.
clear, builtin_function_or_method, Remove all elements from this set.
copy, builtin_function_or_method, Return a shallow copy of a set.
difference, builtin_function_or_method, Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)
difference_update, builtin_function_or_method, Remove all elements of another set from this set.
discard, builtin_function_or_method, Remove an element from a set if it is a member.

If the element is not a member, do nothing.
intersection, builtin_function_or_method, Return the intersection of two sets as a new set.

(i.e. all elements that are in both sets.)
intersection_update, builtin_function_or_method, Update a set with the intersection of itself and another.
isdisjoint, builtin_function_or_method, Return True if two sets have a null intersection.
issubset, builtin_function_or_method, Report whether another set contains this set.
issuperset, builtin_function_or_method, Report whether this set contains another set.
pop, builtin_function_or_method, Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
remove, builtin_function_or_method, Remove an element from a set; it must be a member.

If the element is not a member, raise a KeyError.
symmetric_difference, builtin_function_or_method, Return the symmetric difference of two sets as a new set.

(i.e. all elements that are in exactly one of the sets.)
symmetric_difference_update, builtin_function_or_method, Update a set with the symmetric difference of itself and another.
union, builtin_function_or_method, Return the union of sets as a new set.

(i.e. all elements that are in either set.)
update, builtin_function_or_method, Update a set with the union of itself and others.


脚註 編集

  1. ^ 3.10.1 Documentation » The Python Language Reference » 3. Data model ¶3.2. The standard type hierarchy” (2021年12月16日). 2021年12月16日閲覧。