【Python】`&`と`|`演算子について

f:id:hira98:20190717051222p:plain

【結論】

  • &|はビット演算子で、int型set型(集合演算)で使うことができる。

【目次】

はじめに

Ruby|,||,&,&&を解説している記事見つけたので、同じ内容をPythonで試してみた結果をまとめました。

||&&は、Rubyでの解説記事や以前Javaでまとめた内容と同じだったのでスルーします。

hira98.hatenablog.com

数値の場合は

>>> 2 & 4
0
>>> 2 | 4
6

数値の場合、先頭に0bをつけると二進数で記述でき、かつbin()関数に渡すと結果も2進数で表示できるので、論理演算されていることより分かりやすくなります。

>>> bin(0b0010 & 0b1010)
'0b10'
>>> bin(0b0010 | 0b1010)
'0b1010'

文字の場合

>>> "2" & "10"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'str' and 'str'
>>> "2" | "10"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'

集合演算子の場合

>>> a = {1,2,3}
>>> b = {3,4,5}
>>> a & b
{3}
>>> a | b
{1, 2, 3, 4, 5}

辞書型の場合

>>> a = {1:10, 2:20, 3:30}
>>> b = {3:30, 4:40, 5:50}
>>> a & b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'dict' and 'dict'
>>> a | b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'dict' and 'dict'
>>> 

リスト型の場合

>>> a = [1,2,3]
>>> b = [3,4,5]
>>> a & b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'list' and 'list'
>>> a | b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'list' and 'list'

タプル型の場合

>>> a = (1,2,3)
>>> b = (3,4,5)
>>> a & b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'tuple' and 'tuple'
>>> a | b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'tuple' and 'tuple'

参考情報

Rubyの「|」「&」「||」「&&」の違い - 毎日投稿する技術ブログ(WEB系)

Pythonで2進数、8進数、16進数の数値・文字列を相互に変換 | note.nkmk.me

さいごに

本当は業務でやっている内容をブログにまとめたいのですが、次の理由により断念しました。

  1. 業務内容をそのままブログにアップするのはNGなので、ブログに書く内容が一般的な情報かを判断する必要がある。

  2. 業務内容がニッチすぎて、どこまでブログに書いていいのか判断に迷う。

  3. 業務を行う上で一般知識についてブログにまとめれるほど身についていない。

1,2関しては現状では対策の打ちようがないので、まずは3に注力して、なんとか120日は毎日ブログ書きたいです。

…開発業務をこなしながら毎日ブログ書いてる人スゲェーわ。