0
0

More than 1 year has passed since last update.

Pythonのアンパックの基礎

Posted at

アンパックとは

From ChatGPT:

Pythonのアンパック(Unpacking)は、シーケンス(リストやタプルなど)やイテラブル(iterable)オブジェクトから要素を取り出して、それぞれの変数に代入する操作です。アンパックは一度に複数の変数への代入を行うことができます。

アンパックは、Python言語の特徴の一つで、複数の戻り値を戻せる関数を作成できるというとても便利な機能です。

li, num_val, string_val = func(args1, args2)

戻り値の一部を省略する場合は以下

li, num_val, _ = func(args1, args2)

戻り値がそれぞれ異なる型でもOK

事例1

基準日を基に月、年度、月初め、月末、年度初、年度末をそれぞれ戻す関数

def get_cal_info():
    '''基準日の計算
    Returns:
        base_day:基準日
        base_month:基準月
        base_year: 基準年度
        start_month:月初め
        end_month:月末
        start_year:年度始
        end_year:年度末
    '''
    # 実行日を基準(1日前)
    base_day = pd.Timestamp.today().date()-timedelta(days=1)

    # 月のデータを取得
    base_month = int(base_day.strftime("%m"))

    # 月始め
    start_month = base_day.replace(day=1) 
    # 月末
    end_month = base_day.replace(day=1) + relativedelta(months=1)+ timedelta(seconds=-1)

    # 年度計算
    if base_month > 4:
        base_year = int(base_day.strftime('%Y'))
    else:
        base_year = int(base_day.strftime('%Y')) - 1

    base_month = base_day.strftime('%Y-%m')
    base_day = base_day.strftime('%Y%m%d')
    start_year = pd.Timestamp(base_year,4,1).strftime('%Y%m%d')
    end_year = pd.Timestamp(base_year+1,3,31).strftime('%Y%m%d')
    start_month = start_month.strftime('%Y%m%d')
    end_month = end_month.strftime('%Y%m%d')
    
    return base_day, base_month, base_year, start_month, end_month, start_year, end_year

呼び出し側

# 基準日、年度、年度初め、年度末を使用する場合のアンパック
base_day, _, base_year, _, _, start_year, end_year = get_cal_info()
# 基準日、基準月、月初め、月末を使用する場合のアンパック
base_day, base_month, _, start_month, end_month, _, _ = get_cal_info()

事例2

NumpyのFlattenを使って多次元の配列を1次元に変更する

import numpy as np

def test():
    l = [[1,2],[3,4],[5,6]]
    li = np.array(l)
    re = li.flatten()
    re2 = list(re)
    return re, re2

np_array, li = test()
print(np_array)
print(li)

特殊事例

以下の事例の場合、すべてのローカル変数を辞書型に格納して戻り値にする

import numpy as np

def test2():
    l = [[1,2],[3,4],[5,6]]
    li = np.array(l)
    re = li.flatten()
    re2 = list(re)
    return locals()

result = test2()

for k,v in result.items():
    print(k)
    print(v)

print(result['re'])

実行結果

l
[[1, 2], [3, 4], [5, 6]]
li
[[1 2]
 [3 4]
 [5 6]]
re
[1 2 3 4 5 6]
re2
[1, 2, 3, 4, 5, 6]
[1 2 3 4 5 6]

アンパックとZIPの応用事例

以前の記事をご参照ください。

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