Python print関数の書式 #11 pprint
株式会社リュディアです。今回は pprint についてです。前回に続き print 関数の書式ではないのですが、書式に近い概念だと思うのでついでに紹介しておきます。私はデバグのときによく使います。
前回までの print 関数の書式のまとめへのリンクは以下を参考にしてください。
早速以下の例を見てください。
from pprint import pprint
ld_a = [{'fruit':'Apple', 'count':2, 'country':'Japan'}, {'fruit':'Orange', 'count':4, 'country':'USA'}, {'fruit': 'Banana', 'count':8, 'country':'Philippines'}]
print(ld_a)
pprint(ld_a)
# print の出力
# [{'fruit': 'Apple', 'count': 2, 'country': 'Japan'}, {'fruit': 'Orange', 'count': 4, 'country': 'USA'}, {'fruit': 'Banana', 'count': 8, 'country': 'Philippines'}]
# pprint の出力
# [{'count': 2, 'country': 'Japan', 'fruit': 'Apple'},
# {'count': 4, 'country': 'USA', 'fruit': 'Orange'},
# {'count': 8, 'country': 'Philippines', 'fruit': 'Banana'}]
どうでしょうか? print の出力は単に羅列なのですが、pprint は人間が見やすいように整形されていることがわかりますね。
次はよく使う2次元のリストです。以下の例を見てください。
from pprint import pprint
l_2d = [[0, 1, 2, 3, 4], [10, 20, 30, 40, 50], [200, 300, 400, 500, 600]]
print(l_2d)
pprint(l_2d)
pprint(l_2d, width=30)
# print の出力
# [[0, 1, 2, 3, 4], [10, 20, 30, 40, 50], [200, 300, 400, 500, 600]]
#
# pprint の出力
# [[0, 1, 2, 3, 4], [10, 20, 30, 40, 50], [200, 300, 400, 500, 600]]
#
# pprint に width=30を指定した場合の出力
# [[0, 1, 2, 3, 4],
# [10, 20, 30, 40, 50],
# [200, 300, 400, 500, 600]]
個人的には pprint だけではうまく出力されなかったので驚きました。これが仕様なのですかね? Anaconda3 の Jupyter notebook で試しています。文字幅を 30 と指定すると2次元のリストがリスト要素毎に改行されて出力されました。
pprint にはいろいろなオプションがあるのですが、pprint というものがある、という紹介だけですので、今回のまとめはここまでとします。
では、ごきげんよう。