0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonのアンパッキングの基本

0
Posted at
演算子 位置 機能
* 関数呼び出し / リスト・タプルリテラル / 代入 反復可能オブジェクトを個々の要素に展開 f(*[1,2])f(1,2)
** 関数呼び出し / 辞書結合 キーと値のペアを展開 g(**{'a':1,'b':2})g(a=1,b=2)

*イテラブル(リスト・タプル・セットなど)のみ展開でき、
**辞書のみ展開できます。
数値・文字列など他のオブジェクトに直接書くと掛け算・演算になるので注意。


関数呼び出し例

def greet(greeting, name):
    print(f"{greeting}, {name}!")

args = {"name": "Alice"}
greet(greeting=args["name"], name="Bob")        # Alice, Bob!
# あるいは
greet(**{"greeting": args["name"], "name": "Bob"})

リスト・タプルの結合

base = [1, 2]
extended = [*base, 3, 4]      # [1, 2, 3, 4]

辞書の結合

d1 = {"x": 1, "y": 2}
d2 = {"y": 20, "z": 3}
merged = {**d1, **d2}          # {'x': 1, 'y': 20, 'z': 3}

代入で残りをまとめる

values = [10, 20, 30, 40]
first, *middle, last = values
# first=10, middle=[20,30], last=40

よくあるミス

ミス エラー 対処
** をリストに使う TypeError: 'list' object is not a mapping リストは * のみ使用
**None を展開 TypeError: 'NoneType' object is not a mapping None が渡る場合は ** を外す
辞書のキーが関数引数と一致しない TypeError: got an unexpected keyword argument... キーを合わせるか、** を使わない
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?