【问题标题】:Sorting a list of dictionary key objects with custom comparison function in Python在 Python 中使用自定义比较函数对字典键对象列表进行排序
【发布时间】:2015-03-19 02:31:45
【问题描述】:

我正在将一些代码从 C++ 移植到 Python,这些代码依赖于 C++ 使用自定义比较函数对映射中的键进行排序。我假设我可以简单地使用 Python 字典,然后在键上使用 sorted(),使用等效函数作为 key= to sorted()。但是,无论我如何尝试,键在 Python 中以不同的顺序遍历。

C++ 代码是我在 gitub 上找到的 gSpan 的一些随机实现here。请参阅 src/gspan.h 和 src/graph.h 中的 ProjectionMap 和 struct dfs_code_t。

我的简化 python 代码如下,包括 C++ 代码中两个比较函数的直接副本:

dfs_code = collections.namedtuple('dfs_code',
            ['fromn','to','from_label','edge_label','to_label'])

def dfs_code_compare(a, b):
    if a.from_label != b.from_label:
        return a.from_label < b.from_label
    else:
        if a.edge_label != b.edge_label:
            return a.edge_label < b.edge_label
        else:
            return a.to_label < b.to_label

def dfs_code_backward_compare(a, b):
    if a.to != b.to:
        return a.to < b.to
    else:
        return a.edge_label < b.edge_label

# code that fills in a dictionary called pm

for pm in sorted(projection_map, key=functools.cmp_to_key(dfs_code_compare)):
        print pm

上面的python代码产生以下顺序:

dfs_code(fromn=0, to=1, from_label=1, edge_label=0, to_label=3)
dfs_code(fromn=0, to=1, from_label=2, edge_label=3, to_label=2)
dfs_code(fromn=0, to=1, from_label=1, edge_label=3, to_label=3)
dfs_code(fromn=0, to=1, from_label=1, edge_label=1, to_label=2)
dfs_code(fromn=0, to=1, from_label=2, edge_label=1, to_label=3)
....

这 a) 与 C++ 代码不同,b) 与我对比较函数的期望完全不同(例如,我希望 1 的所有 from_labels 都在前面组合在一起)。有任何想法吗?和functools.cmp_to_key有关系吗?

【问题讨论】:

    标签: python c++ dictionary


    【解决方案1】:

    在python中,比较函数必须返回一个负数、正数或零值,指示第一个元素是小于、大于还是等于第二个元素。由于 python 的

    您可以重写比较函数以使用此约定,但编写关键函数可能更容易。

    例如,dfs_code_compare 可以转换成这个键函数:

    def dfs_code_key(pm):
        return (pm.from_label, pm.edge_label, pm.to_label)
    

    并像这样使用:

    for pm in sorted(projection_map, key=dfs_code_key):
        pm
    

    【讨论】:

    • 呸!我知道这是显而易见的!你当然是对的,我完全错过了。
    猜你喜欢
    • 2013-06-28
    • 2020-07-09
    • 2020-07-11
    • 1970-01-01
    • 2018-08-26
    • 2015-10-23
    • 2011-07-09
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多