LoginSignup
0
0

More than 3 years have passed since last update.

ネスト化された辞書の値(Value)の合計を計算する

Last updated at Posted at 2019-06-12

やりたいこと

ネスト化された辞書の値(Value,ただし数値のみ)の合計を計算したい.なお,事前にネストの深さがわかっていないとする.

たとえば以下のような辞書xを考える.

x = {'a': 1.1,
     'b': {
         'c': [1, 1],
         'd': {
             'e': (1, 1),
             'f': {
                 'g': 'foo'
             }
         }
     }}

この場合の合計は5.1になる.

方法

再帰関数を使う.

def f(x):
    y = 0
    if isinstance(x, int) or isinstance(x, float):
        y += x
    elif isinstance(x, tuple) or isinstance(x, list):
        for _x in x:
            y += f(_x)
    elif isinstance(x, dict):
        for v in x.values():
            y += f(v)
    else:
        pass
    return y
assert f(x) == 5.1  # OK

感想

再帰関数最近使ってなかったので完全に忘れていた

0
0
2

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