python - 如何检查列表是否包含具有相同键的dict元素
问题描述
我想检查我的列表是否包含具有相同两个键值的元素。例如,我想通过category
和weight
在下面的列表中进行聚合:
products = [
{"id": 1, "category": "Furniture", "weight": 3.22},
{"id": 2, "category": "Furniture", "weight": 4.55},
{"id": 3, "category": "Furniture", "weight": 3.22},
{"id": 4, "category": "Garden", "weight": 3.22},
]
上面的示例应该返回 True
products = [
{"id": 1, "category": "Furniture", "weight": 3.22},
{"id": 2, "category": "Furniture", "weight": 4.55},
{"id": 4, "category": "Garden", "weight": 3.22},
]
上面的示例应该返回 False
解决方案
一种可能的方法是首先编写一个通用函数来检测可迭代对象是否包含重复项:
def has_duplicates(it):
"""Returns whether the iterable contains any duplicates.
The items of the iterable need to be hashable."""
seen = set()
for x in it:
if x in seen:
return True
seen.add(x)
return False
要将此功能应用于您的问题,您需要提取要比较的键,例如
from operator import itemgetter
key_function = itemgetter("category", "weight")
print(has_duplicates(map(key_function, products)))
True
这将为您的第一个示例和第二个示例打印False
。
请注意,这将比较精确的身份,这对于浮点数通常是一个坏主意。
推荐阅读
- r - 使用 dplyr 在组内进行总结
- mysql - 如何在 NestJS 和 Knex 中构建复杂的 MySQL 查询
- java - Android studio解析json对象
- graphql - GraphQL 拼接 VS 合并模式
- python - 在保留其他值的同时使用列表聚合/删除行中的字符串(python)?
- facebook-opengraph - 网页预览仅限于某些平台
- java - 如何使用自己的快速排序来决定具有多个输入数据的任务
- python - 如何在不和谐的文本频道上发送嵌入的 Facebook 视频 URL
- react-native - React Native 的 NetInfo 在 iOS 和 Android 上的不同行为
- mysql - 为什么这个结果会发生两次?相隔几分钟