擅长:python、mysql、java
<p>对于给定的数据结构,您将不得不重复遍历第二个字典列表中的项,这相对效率较低。你关心的是给定的电话号码是否已经存在于第二个字典列表中。重复测试给定值是否存在的最有效的数据结构是<code>set</code>(或者<code>dict</code>,如果您可能需要从电话号码索引回更多信息)。因此,我将按以下方式进行:</p>
<pre><code>a = [a1, a2, a3]
b = [b1, b2, b3]
a_phone_numbers_set = set(d['phone'] for d in a])
b_phone_numbers_set = set(d['phone'] for d in b])
result_A_minus_B = [d for d in a if d['phone'] not in b_phone_numbers_set]
result_B_minus_A = [d for d in b if d['phone'] not in a_phone_numbers_set]
</code></pre>
<p>或者,如果我想创建一个函数:</p>
^{pr2}$
<p>或者,您可以使用任意键:</p>
<pre><code>def unmatched_entries(list1, list2, matching_key):
existing_entries = set(d[matching_key] for d in list2 if matching_key in d)
return [d for d in list1 if matching_key in d and d[matching_key] not in existing_entries]
</code></pre>
<p>该版本总是跳过list1中没有定义请求的键的条目-其他行为是可能的。在</p>
<p>为了匹配简短出现的注释所暗示的多个键,我将使用一组值的元组:</p>
<pre><code>a_match_elements = set((d['phone'], d['email']) for d in a])
result_B_minus_a = [d for d in b if (d['phone'], d['email']) not in a_match_elements]
</code></pre>
<p>同样,这可以被推广到处理一系列键。在</p>