0

我有一个包含超过 100000 个键的巨大图表,因此效率是一个大问题。我正在检查每个键的值,对于每个值,我希望它成为另一个字典中的键,值是剩余的值......例如..

graph = {'foobar': ['1', '2', '3']}
result = {'1' : ['2', '3'], '2' : ['1', '3'], '3' : ['1', '2']}  #in no particular order

这是我目前的代码...

for i in heroDict.values():
    for j in i:
        if graph.has_key(j):
            tempDict = copy.deepcopy(i)
            tempDict.remove(j)
            heroList = tempDict
            graph[j] += heroList
        else:
            tempDict = copy.deepcopy(i)
            tempDict.remove(j)
            heroList = tempDict
            graph[j] = heroList
return graph

'heroDict' 是一个类似于示例的字典,除了非常非常大。

我遇到的问题是我的代码运行非常缓慢,因为我正在执行 deepcopy()。例如,对于 foobar 示例,我将 '1' 作为键。我将 ['1', '2', '3'] 复制到一个临时字典中,因此对它的更改不会影响我返回的最终字典。然后我从 ['1', '2', '3'] 中删除密钥并将密钥 '1' 分配给它。所以我留下了 {'1' : ['2', '3']} 这是我想要的,但它花费了太长时间,因为它迭代了 100000+ 次。

我的最后一个问题是,我可以以任何方式改进它以使其运行得更快吗?

任何帮助是极大的赞赏。

4

1 回答 1

4

排列包含在itertools.

您的示例中的典型用途是:

>>> from itertools import permutations
>>> values = graph['foobar']
>>> result = {x[0]:x[1:] for x in permutations(values)}
>>> print result
{'1': ('3', '2'), '2': ('3', '1'), '3': ('2', '1')}

适用于 foobar 中的任意数量的值。Permutations 是一个生成器,因此您可以一次调用一个项目,而不是一次生成整个 dict。

不过,不确定那会有多快。

于 2013-05-24T12:11:38.687 回答