0

假设我有一个看起来像这样的列表,但深度和复杂性可能会有所不同:

inc = {'root': 10, 
    'values': {
         'left': {8: {
             'left': {
                 6: {
                    'left': 5, 
                    'right': 11}
                  }, 
             'right': {
                  10: {
                     'left': 2, 
                     'right': 11}
               }}}, 
         'right' : {
                  12: {
                     'left': 5, 
                     'right': 20}
                  }}}

我需要做的是遍历它,找到最左边的值和最左边的值(即通过访问字典的“左”元素达到的值)并交换它们。递归遍历字典以查找值不是问题。问题是在我确定需要更改的内容之后找到必要的值。

用于迭代的函数:

leftmost = 0
lowest = 0

def walk_dict(d):
    global leftmost, lowest

    for k,v in sorted(d.items()):
        if isinstance(v, dict):
            walk_dict(v)
        else:
            if k == 'left':
                if leftmost == 0:
                    leftmost = v
                if v < lowest:
                    lowest = v
4

1 回答 1

1

与其直接保存值,不如让字典保存它们,这样您就可以在最后交换值,例如:

[in the loop]
  if k == 'left':
    if not leftmost:
      leftmost = d
    if v < lowest['left']:
      lowest = d

# swap
lefmost['left'], lowest['left'] = lowest['left'], lefmost['left']

Also I'm not sure about your definition of leftmost, but if it means the least deep key that equals to "left", your code is wrong as it simply grabs the first value found during the depth-first traversal. To overcome the problem you could keep the current depth and compare it as well to determine if the leftmost value should be overwritten.

于 2013-03-22T22:46:27.333 回答