[英]Efficient way to find *ordered* intersection of dictionaries starting at top (or an arbitrary index)?
我正在寻找一种有效的方法来查找顺序很重要的两个 Python 词典的交集,从顶部开始。 换句话说,遍历字典,一旦它们的键或值不同,就停止。 我认为这通过一些例子是最清楚的。
{a: 1, b: 0}
和{a: 1, b: 1}
的交集显然是{a: 1}
。{a: 1, b: 0, c: 1}
和{a: 1, c: 1, b: 0}
的交集就是{a: 1}
因为顺序很重要。{a: 1, b: 0}
和{b: 0, c: 1}
的交集是空的,因为它们不在同一个键上开始。我有以下功能有效,但我想知道是否有更简单/更快的方法。
def find_ordered_intersection(d0, d1):
d1keys = list(d1.keys())
intersection = {}
for i, (k, v) in enumerate(d0.items()):
if (k == d1keys[i]) and (v == d1[k]):
intersection.update({k:v})
else:
return intersection
ps 我很难简洁地描述我的目标。 如果有人有编辑,请随意。
如果您可以依赖插入顺序,则可以使用takewhile和dict执行以下操作:
from itertools import takewhile
def intersection(a, b):
return dict(kb for ka, kb in takewhile(lambda x: x[0] == x[1], zip(a.items(), b.items())))
print(intersection({'a': 1, 'b': 0, 'c': 1}, {'a': 1, 'c': 1, 'b': 0}))
print(intersection({'a': 1, 'b': 0, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}))
print(intersection({'a': 1, 'b': 0}, {'a': 1, 'b': 1}))
print(intersection({'a': 1, 'b': 0, }, {'b': 0, 'c': 1}))
输出
{'a': 1}
{'a': 1}
{'a': 1}
{}
这应该更容易理解。
def find_ordered_intersection(d0, d1):
d0keys = list(d0.keys())
d1keys = list(d1.keys())
size = min(len(d0), len(d1))
dic = {}
for i in range(size):
key0 = d0keys[i]
key1 = d1keys[i]
if key0 != key1:
break
elif d0[key0] != d1[key1]:
break
else:
dic[key0] = d0[key0]
return dic
def find_ordered_intersection(d0, d1):
intersection = {tpl[0][0]: tpl[0][1] for tpl in zip(d0.items(), d1.items()) if (tpl[0][0] == tpl[1][0]) and (tpl[0][1] == tpl[1][1])}
return intersection
#The intersection of {a: 1, b: 0} and {a: 1, b: 1} is obviously {a: 1}.
#The intersection of {a: 1, b: 0, c: 1} and {a: 1, c: 1, b: 0} is just {a: 1} since order matters.
#The intersection of {a: 1, b: 0} and {b: 0, c: 1} is empty because they don't start on the same key.
d0 = {'a': 1, 'b': 0}
d1 = {'a': 1, 'b': 1}
print(find_ordered_intersection(d0, d1))
d2 = {'a': 1, 'b': 0, 'c': 1}
d3 = {'a': 1, 'c': 1, 'b': 0}
print(find_ordered_intersection(d2, d3))
d4 = {'a': 1, 'b': 0}
d5 = {'b': 0, 'c': 1}
print(find_ordered_intersection(d4, d5))
输出:
{'a': 1}
{'a': 1}
{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.