【发布时间】:2019-07-10 13:42:20
【问题描述】:
在给定的列表中:
unmatched_items_array = [{'c': 45}, {'c': 35}, {'d': 5}, {'a': 3.2}, {'a': 3}]
查找所有“键”对并打印出来,如果没有找到给定字典的对,则打印出该字典。
到目前为止,我设法编写的内容有点像作品,但它会继续测试列表中的某些项目,即使它们已经过测试。不知道怎么解决。
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}
我在这里做错了什么?
【问题讨论】:
-
你为什么需要它?将数据结构化为单对字典列表这一事实是您无法更改的吗?
-
无法真正改变这一点。这就是数据进来的方式。但可以将其处理为其他东西。不知道哪种数据结构会更好。只要我最后得到匹配对
标签: python loops dictionary