1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonの集合演算

Posted at

Pythonのsetでの集合演算方法を整理する。

#【set

  • 集合を生成する。
  • リテラルは、波カッコ「{}」になる。
X = set([1,2,3,4,5,6,1,1,1])
print(X)
# {1, 2, 3, 4, 5, 6}

Y = {9,9,9,4,5,6,7,8,9}
print(Y)
# {4, 5, 6, 7, 8, 9}

<set>.union(set)

  • 和集合(OR)
  • 演算子「|」で代用できる。
Z = X.union(Y)
print(Z)
# {1, 2, 3, 4, 5, 6, 7, 8, 9}

Z = X | Y
print(Z)
# {1, 2, 3, 4, 5, 6, 7, 8, 9}

<set>.intersection(set)

  • 積集合(AND)
  • 演算子「&」で代用できる。
Z = X.intersection(Y)
print(Z)
# {4, 5, 6}

Z = X & Y
print(Z)
# {4, 5, 6}

<set>.symmetric_difference(set)

  • 対称差(XOR)
  • 演算子「^」で代用できる。
Z = X.symmetric_difference(Y)
print(Z)
# {1, 2, 3, 7, 8, 9}

Z = X ^ Y
print(Z)
# {1, 2, 3, 7, 8, 9}

<set>.difference(set)

  • 差集合
  • 演算子「-」で代用できる。
Z = X.difference(Y)
print(Z)
# {1, 2, 3}

Z = X - Y
print(Z)
# {1, 2, 3}

<set>.issubset(set)

  • 下位集合(部分集合)かの判定
  • 演算子「<=」で代用できる。
X = {1,2,3}
Y = {1,2,3,4,5}

Z = X.issubset(Y)
print(Z)
# True

Z = X <= Y
print(Z)
# True

<set>.issuperset(set)

  • 上位集合の判定
  • 演算子「>=」で代用できる。
X = {1,2,3,4,5}
Y = {1,2,3}

Z = X.issuperset(Y)
print(Z)
# True

Z = X >= Y
print(Z)
# True

<set>.isdisjoint(set)

  • 共通要素が無いかの判定
X = {1,2,3}
Y = {4,5,6}

Z = X.isdisjoint(Y)
print(Z)
# True

備考

本記事はブログ「雑用エンジニアの技術ノート」からの移行記事です。先のブログは削除予定です。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?