【发布时间】: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