要求是迭代python中的每对唯一键组合,并获得每对键的值的交集列表。为了达到这个目的,我迭代了两次密钥,在第二次迭代中,我绕过所有密钥值较小的密钥与第一次迭代的密钥进行比较 -
for key1, val1 in dict.iteritems():
for key2, val2 in dict.iteritems():
if key2 <= key1:
continue
else:
#vertices common to both key1 and key2 will be
#in intersection list of its values
neighbours = [val for val in val1 if val in val2]
#--Further processing on list of neighbours
正如在其他帖子中所提到的,我可以创建字典键的组合并迭代它,但因为我必须同时处理值,所以我使用上述方法。
实现这一目标最有效和最有效的方式是什么?
答案 0 :(得分:1)
有更好的工具可供选择;使用itertools.combinations()
generator将每个密钥与其他密钥配对:
from itertools import combinations
for (key1, val1), (key2, val2) in combinations(dictionary.items(), 2):
演示:
>>> from itertools import combinations
>>> dictionary = {'foo': 'bar', 'spam': 'eggs', 'monty': 'python'}
>>> for (key1, val1), (key2, val2) in combinations(dictionary.items(), 2):
... print('Combining {!r}: {!r} with {!r}: {!r}'.format(key1, val1, key2, val2))
...
Combining 'foo': 'bar' with 'monty': 'python'
Combining 'foo': 'bar' with 'spam': 'eggs'
Combining 'monty': 'python' with 'spam': 'eggs'
您可能希望使用集来计算交叉点:
neighbours = set(val1).intersection(val2)