我有一个由超过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多次。
我的最后一个问题是,我能以任何方式改进它,使它运行得更快吗?
排列包含在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是一个生成器,因此您可以一次调用一个项,而不是一次生成整个字典。
不知道会有多快