Help us understand the problem. What is going on with this article?

Pythonの集合演算

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

備考

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

nezuq
ITエンジニア。仕事や趣味で学んだ事を共有しています。Enjoy Tech! Update World!
https://www.slideshare.net/nezuQ/presentations
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした