【问题标题】:Python: Using dictionary to print dependent variablesPython:使用字典打印因变量
【发布时间】:2016-02-09 07:09:16
【问题描述】:

给我一​​个问题如下:

B = C, D
A = B
C = E

意思是B依赖于变量C和D,而A依赖于B,依此类推。变量 E 和 D 是独立的。

'A' 的输入应该返回:

E, C, D, B, A

列出所有因变量。为了解决这个问题,我首先定义了一个字典来轻松地迭代这个条件:

letter = {'A' : ['B'], 'B' : ['C', 'D'], 'C' : ['E']}

但是,我现在坚持如何循环以有效地打印所有子项。我认为这是错误的,但我认为我可能会朝着正确的方向前进:

def problem(value):
    letter = {'A' : ['B'], 'B' : ['C', 'D'], 'C' : ['E']}
    for i in letter:
        if i != value:
            continue
        if len(letter[i]) > 1:
            for k in letter:
                print("".join(letter[k]), k)
        print("".join(letter[i]), i)

请帮忙!

【问题讨论】:

标签: python dictionary


【解决方案1】:

在快速搜索后从http://code.activestate.com/recipes/576570-dependency-resolver/ 窃取。

def dep(arg):
    '''
        Dependency resolver

    "arg" is a dependency dictionary in which
    the values are the dependencies of their respective keys.
    '''
    d=dict((k, set(arg[k])) for k in arg)
    r=[]
    while d:
        # values not in keys (items without dep)
        t=set(i for v in d.values() for i in v)-set(d.keys())
        # and keys without value (items without dep)
        t.update(k for k, v in d.items() if not v)
        # can be done right away
        r.append(t)
        # and cleaned up
        d=dict(((k, v-t) for k, v in d.items() if v))
    return r

if __name__=='__main__':
    d=dict(
        a=('b','c'),
        b=('c','d'),
        e=(),
        f=('c','e'),
        g=('h','f'),
        i=('f',)
    )
    print dep(d)

【讨论】:

    【解决方案2】:

    您在另一个列表中拥有一个列表。在另一个 for 循环中编写一个嵌套的 for 循环,然后通过您的测试逻辑运行它。对于外部列表,遍历内部列表的每个部分,然后移动到外部列表的下一部分。

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 2016-06-07
      • 2011-06-27
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多