在给定的列表中:
unmatched_items_array = [{'c': 45}, {'c': 35}, {'d': 5}, {'a': 3.2}, {'a': 3}]
找到所有的“key”对,打印输出它们。如果给定的字典中没有配对,则打印出该字典。
目前我写的代码有点能用,但是它会不停地测试一些已经测试过的列表项。不确定如何修复它。
for i in range(len(unmatched_items_array)):
for j in range(i + 1, len(unmatched_items_array)):
# when keys are the same print matching dictionary pairs
if unmatched_items_array[i].keys() == unmatched_items_array[j].keys():
print(unmatched_items_array[i], unmatched_items_array[j])
break
# when no matching pairs print currently processed dictionary
print(unmatched_items_array[i])
输出:
{'c': 45} {'c': 35}
{'c': 45}
{'c': 35}
{'d': 5}
{'a': 3.2} {'a': 3}
{'a': 3.2}
{'a': 3}
输出应该是什么:
{'c': 45} {'c': 35}
{'d': 5}
{'a': 3.2} {'a': 3}
我在这里做错了什么?