【问题标题】:Recursing python dictionaries with yield from to generate list of nested dictionary keys使用 yield from 递归 python 字典以生成嵌套字典键列表
【发布时间】:2021-10-08 15:08:02
【问题描述】:

我想为字典中的每个值生成一个唯一嵌套键的列表,这样:

input_dict = {"a": {"b": "c", "d": {"e": "f"}}, "f": "g"}

expected_result = [["a", "b"], ["a", "d", "e"], ["f"]]

我认为沿着这些思路的东西会起作用,将每个键附加到一个列表并递归直到达到一个值。此时我会生成一个列表并继续。

def _i(itr, list_of_keys):
    if list_of_keys is None:
        list_of_keys = []

    if isinstance(itr, dict):
        # For each dict, add the key to the list, and recurse
        for key, value in itr.items():
            list_of_keys.append(key)
            yield from _i(value, list_of_keys)
    else:
        # If not a dict, then at the end of a series of keys, yield the list
        yield list_of_keys
        list_of_keys = []

但是运行时,结果是所有的唯一键

x = _i(input_dict, list_of_keys=None)
list(x)

 [['a', 'b', 'd', 'e', 'f'],
 ['a', 'b', 'd', 'e', 'f'],
 ['a', 'b', 'd', 'e', 'f']]

我想我一定遗漏了一些关于屈服/输入参数如何工作的东西

【问题讨论】:

  • 正如@schowabaseggl 解释的那样,您在这里处理的是一个可变列表。使用他们的方法或将数据结构更改为元组都会得到预期的结果。

标签: python yield yield-from


【解决方案1】:

你一直在修改同一个列表对象(在最后重新分配一个局部变量对任何递归调用都没有影响)!没有结转变量的更简单的方法是:

def _i(obj):
    if isinstance(obj, dict):
        for k, v in obj.items():
            for keys in _i(v):
                yield [k] + keys
    else:
        yield []

>>> list(_i(input_dict))
[['a', 'b'], ['a', 'd', 'e'], ['f']]

【讨论】:

  • 啊,我明白了,在列表被清除之前已经调用了_i,因此它对结果没有影响。不错的解决方案,干杯
猜你喜欢
  • 2016-11-05
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 2021-12-04
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多