2
3

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の三項演算子の効きかたにびっくりした

Last updated at Posted at 2017-01-25

よく考えなくても当たり前のことですし、多分皆さまは知ってることだと思うのですが面白かったので投稿します。

Pythonで正誤判定するときに以下のように三項演算子を使いました。

hoge.py
print 'No.' + str(i) + ' is ' + 'True' if test[i][1] == res else 'False' + ' (true label:' + test[i][1] + ', predicted label: ' + res + ')'

結果、

No.1 is True
False (true label: 3, predicted label: 0)
No.3 is True
No.4 is True
No.5 is True
No.6 is True
No.7 is True
No.8 is True
No.9 is True
No.10 is True
No.11 is True
False (true label: 1, predicted label: 2)
No.13 is True
No.14 is True
False (true label: 1, predicted label: 2)

正誤ごとの結果が演算子の前後にあるので前の全文と後ろの全文に効いてくるんですね。
カッコで囲めば期待通りに動くのですが、この使い方でも色々できそうだなぁと思いました。おしまい。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?