Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查列表是否包含具有相同键的dict元素_Python_Python 3.x_Itertools - Fatal编程技术网

Python 如何检查列表是否包含具有相同键的dict元素

Python 如何检查列表是否包含具有相同键的dict元素,python,python-3.x,itertools,Python,Python 3.x,Itertools,我想检查我的列表是否包含具有相同两个键值的元素。 例如,我想通过下表中的类别和权重进行聚合: products = [ {"id": 1, "category": "Furniture", "weight": 3.22}, {"id": 2, "category": "Furniture", "weight": 4.55}

我想检查我的列表是否包含具有相同两个键值的元素。 例如,我想通过下表中的
类别
权重
进行聚合:

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

一种可能的方法是首先编写一个泛型函数来检测iterable是否包含重复项:

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


请注意,这将比较精确标识,而对于浮点数来说,这通常是一个坏主意。

一种可能的方法是首先编写一个通用函数来检测iterable是否包含重复项:

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


请注意,这将比较精确标识,而对于浮点数,这通常是一个坏主意。

请用您尝试过的代码更新您的问题。您想如何比较两个字典?通过键“category”和“weight”而不是“id”?查看
itertools.groupby
。您可以按类别和权重分组,然后查看是否有任何组包含多个元素。@adirabargilyes@chepner这需要首先按照所需的键函数进行排序,这很好,但是O(n log n)。请使用您尝试过的代码更新您的问题。您希望如何比较两个词典?通过键“category”和“weight”而不是“id”?查看
itertools.groupby
。您可以按类别和权重分组,然后查看是否有任何组包含多个元素。@adirabargilyes@chepner这需要首先按照所需的键函数进行排序,这很好,但是O(n log n)。