LoginSignup
0
0

More than 5 years have passed since last update.

Python3x: Using Boolean to represent integers such that True ==1; False == 0

Last updated at Posted at 2016-02-24

前回Priority of Boolean Operators: and, or and notで長々とpython3におけるbooleanの特徴を書いたが今回はbooleanを整数として扱えるという特徴について軽く触れてみたいと思う。これもいつもと同様、講義で出くわした内容。

True == 1 False == 0

Booleans represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects.

簡単にいうとここまでとpriority of booleansが前回やった内容。

The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

ここらへんにスコープを定めていこうと思う。どうやらこの数字としてのboolean valueはstr()を除けばどの環境下でもほぼ問題なく数字として扱えるらしい。ただ処理が行われる前にストリングに変えてしまうとそのまま'True'として返ってきてしまうと。

完璧に理解したわけではないが、一番手っ取り早い方法は「まずは試す」ことだと思ったのでいじってたりググったりして気になったことをメモっておきます。

どうやらintというオブジェクトの中にはサブクラスといって同じくintとして扱えることができるオブジェクトが存在するらしい。その一つがboolであると。他にもmethodを使って新たにオブジェクトを定義して使うことも出来るらしいが大分路線が外れていきそうなので今回はパス。

使い方

一番最初に思いついたのがTrue == 1; False == 1だとしたらTruethy value == 1; Falsey Value == 0に簡単変換できる。これが出来るのだとしたらほぼすべての変数の値を変換することができる。何がいいたいのかというと例えば何かのデータを集めてくる作業をしている時などにデータの仕分け作業をしているときにこの特徴をフルに使えそうな気がします。早速ぐぐってみたらそれの根っこになりそうなものを発見。

x = 6
x = int(bool(x))

一言でいうと値がTruethy valueなら1を返しそうでなければ0を返すようになっている。このままだとシンプルすぎて使えない。そこで稚拙ながら自分で役に立ちそうな関数を作ってみたので参考に。

def foo(n, m):
    if n == m:
        return True
    else:
        return False

def feed_me():
    n1 = int(input("yourgf1: feed me some number!: "))
    n2 = int(input("yourgf2: wait feed me some numbers too!: "))
    x = int(bool(foo(n1, n2)))
    print(x) # use return statement if you wish to store data

feed_me()

これでもまだシンプルすぎるかもしれないがfoo()のconditionを変えてあげるだけであとは自分で好きなようにいじれる。あとはこちらから拾ってきた以下のコードを参考にしてくっつけてみると何かもっと使えそうな何かになる気がします。

例えばTrueまたはFalseが要素となっているリストbool_arrayがあったとして、その中のTrueを数えるとき、素直に書けば、

count = 0
for b in bool_array:
    if b is True:
        count += 1

となるところを、
count = sum(bool_array)
と置き換えられます(これがあとで読む人にとって優しいかは別にして)。

これを参考に以下の様なコードをつくってみた。

def im_your_boss(n, m):
    if n == m:
        return True
    else:
        return False

def feed_me():
    n1 = int(input("yourgf1: feed me some number!: "))
    n2 = int(input("yourgf2: wait feed me some number too!: "))
    x = int(bool(im_your_boss(n1, n2)))
    return summation(x)

def summation(y):
    sample_list = []
    sample_list += [y]
    return sum(sample_list)

w = feed_me()
print(w)

こんな一回きりのプログラムではきっと訳にも立たないと思いますが、雰囲気はこんな感じではないかと思っています。結果を全てリストに入れておいてそれをあとでまとめて足してTruethy valueの数を数えるほうが効率的かもしれません。

参考にしたリンク

0
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
0
0