4
1

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 5 years have passed since last update.

【Python】True/Falseを1行で切り替える

Last updated at Posted at 2018-05-31

※コメントでたくさん指摘いただきましたので修正しました。
Pythonでは三項演算子が使えないので、

if $hoge = $hoge ? false : true

みたいに書けません。
1行でトグルしたい場合のやり方をよく忘れるのでメモしておきます

hoge = True
hoge = hoge == False

hoge = True
hoge = not hoge # scikit-learnで使われてたのはこっち

hoge = True
hoge ^= True # hoge = True ^ hoge(XOR)のショートハンド

hoge = True
hoge = bool(1 - int(hoge)) # False

hoge = True
hoge = False if hoge else True # False
4
1
4

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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?