小编Dis*_*ard的帖子

Python:对依赖项列表进行排序

我正在努力研究如果我的问题可以使用内置的sorted()函数解决,或者如果我需要自己做 - 使用cmp的旧学校会相对容易.

我的数据集看起来像:

x = [
('business', Set('fleet','address'))
('device', Set('business','model','status','pack'))
('txn', Set('device','business','operator'))
....

排序规则基本上应该是N和Y的所有值,其中Y> N,x [N] [0]不在x [Y] [1]

虽然我正在使用Python 2.6,其中cmp参数仍然可用,但我正在尝试使这个Python 3安全.

那么,这可以使用一些lambda魔法和关键参数来完成吗?

- ==更新== -

谢谢Eli&Winston!我真的不认为使用钥匙会起作用,或者如果我怀疑它会是一个不太理想的鞋拔解决方案.

因为我的问题是数据库表依赖项,所以我不得不对Eli的代码进行一些小的补充,以从依赖项列表中删除一个项目(在一个设计良好的数据库中,这不会发生,但是谁住在那个神奇的完美世界?)

我的解决方案

def topological_sort(source):
    """perform topo sort on elements.

    :arg source: list of ``(name, set(names of dependancies))`` pairs
    :returns: list of names, with dependancies listed first
    """
    pending = [(name, set(deps)) for name, deps in source]        
    emitted = []
    while pending:
        next_pending = []
        next_emitted = []
        for entry in pending:
            name, …
Run Code Online (Sandbox Code Playgroud)

python sorting topological-sort

13
推荐指数
3
解决办法
3843
查看次数

标签 统计

python ×1

sorting ×1

topological-sort ×1