python - 循环嵌套字典值

标签 python algorithm iterator

我需要能够通过字典的深层嵌套属性进行广度优先循环。这让我走到了那里 ( https://stackoverflow.com/a/10756615/5932433 ),但结果不是我需要的。

给定以下数据结构:

data = {
  "a": {
    "c": 1,
    "d": 3,
  },
  "b": {
    "e": 2,
    "f": 4,
  }
}

我需要一个返回以下内容的方法:

for _, v in cycle(tree_iter(data)):
  print v

# 1 (a -> c)
# 2 (b -> e)
# 3 (a -> d)
# 4 (b -> f)
# 1
# 2
# 3
# 4
# ...etc...

这是我现在为 tree_iter 使用的方法:

def tree_iter(nested):
    for key, value in nested.iteritems():
        if isinstance(value, Mapping):
            for inner_key, inner_value in tree_iter(value):
                yield inner_key, inner_value
        else:
            yield key, value

请注意,不需要保证顺序,只要顺序一致即可。每次迭代都应循环遍历 a/b,然后循环遍历嵌套值。

最佳答案

您当前的代码似乎执行 DFS,因此您可以从 DFS 返回列表列表,压缩它们,然后展平。不是最优雅的,但它应该可以工作。

def tree_iter_dfs(nested):
    for key, value in nested.iteritems():
        if isinstance(value, Mapping):
            yield value.items()
        else:
            yield [(key, value)]

# https://stackoverflow.com/a/952952/5309823
def flatten(l):
    return [item for sublist in l for item in sublist]

def tree_iter_bfs(nested):
    dfs = tree_iter_dfs(nested)
    return flatten(zip(*dfs))

print(list(tree_iter_bfs(data)))
# [('c', 1), ('e', 2), ('d', 3), ('f', 4)]

根据需要将周围的事物更改为可迭代对象;我不知道你用的是什么版本的 Python 等等。

关于python - 循环嵌套字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348191/

相关文章:

python - 我可以更改 BeautifulSoup 将 XML 标签转换为小写的行为吗?

c - 如何在 O(n) 时间内找到在 SORTED 数组中出现奇数次的数字?

algorithm - 这个 n-queens Prolog 解决方案是如何工作的?

c++ - 将临时 istringstream 对象传递给 istream_iterator<string>

java - 单链表上的双向迭代

python - CSV匹配值python

python - Django 查询集按 ISO 周数过滤

php - Apache wildcard SSL cert for wildcard vhost and specifically named vhost

c++ - 自动更正,自动完成功能

c++ - vector::erase() 未按预期工作