Pythonで序数を返す関数

1st. 2nd. 3rd, 4th, 5th ....と序数を表示する必要があったのですが、pythonなら

 def order_n(i): return {1:"1st", 2:"2nd", 3:"3rd"}.get(i) or "%dth"%i

の一行で書けますね。辞書型のgetメソッドは、辞書にない時Noneを返すので、そのときは"%dth"を返せばいいわけです。こういうのを一行でさっと書けるので、pythonは癖になります。

Comments

Popular posts from this blog

Subclassing and Signal connect on a same widget crashes PySide application on exit.

Calling OpenCV functions via Cython from Python 3.X.

Showing CPU/Memory usage on tmux status bar(tmuxのステータスバーにCPUとMemoryの使用状況を表示する)