python unpack

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))

もっと早く知っておきたかった。

同じタグの記事
同じカテゴリの記事

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA