python unpack
今更ながら、tuple, list, dictはunpackできることを知った。
これを利用すると、formatがとても使いやすくなる。
1 2 3 4 5 6 7 8 9 10 11 12 | tpl = ('a', 'b', 'c') lst = ['x', 'y', 'z'] dct = {'aa': 'AA', 'bb': 'BB'} print('tuple 1:{0[1]}'.format(tpl)) print('tuple 2:{1}'.format(*tpl)) print('list 1:{0[1]}'.format(lst)) print('list 2:{1}'.format(*lst)) print('dict 1:{0[bb]}'.format(dct)) print('dict 2:{bb}'.format(**dct)) |
tuple, listは*が一つ、dictは*が2つ必要。
この方法を使えば、関数の引数もlistなどで指定できる。
1 2 3 | import os lst = ('/tmp', 'test.txt') print(os.path.join(*lst)) |
もっと早く知っておきたかった。
同じタグの記事
- BOM付きUTF-8からBOMを除去するpython
- jythonのヒープメモリ設定
- Kotlin1.2.50がリリースされていた
- macOSをHigh Sierraに更新した。スクリプト実行環境のバージョンは変わったのか
- macOSをMojaveに更新した。スクリプト実行環境のバージョンは変わったか
- pathlib.Pathを調べる
- pyenvでpython環境をインストール
- pyenvとvirtualenvでpython環境を構築
- python3で数値のlistを文字列のlistに変換
- pythonからchromeを操作する
同じカテゴリの記事