【发布时间】: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