【问题标题】:Intersection of dictionaries by value ranges按值范围对字典的交集
【发布时间】:2020-10-07 22:00:14
【问题描述】:

我有一本字典,它们的形式如下:

"id_1" : { 
    "_id" : ObjectId("5cefddaae40ed94ea713f7c8"), 
    "derived_from" : ObjectId("5cefddaae40ed94ea713f7c7"), 
    "epsg" : "32723", 
    "active" : True, 
    "name" : "DPA-Time", 
    "range_time_depth" : [ 4648.91338, 5641.545770000001 ], 
    "type" : "Polygon",
    "iline": 6998 
} 

我有一个字典,就像数据库查询:

{
    '_id': { '$in': ['5cefddaae40ed94ea713f7c8','5cefddaae40ed94ea713f7c8'] },
    'iline': {'$gte': 6998, '$lte': 7000}
}

所以,我想检索字典字典中 _id 等于 '5cefddaae40ed94ea713f7c8''5cefddaae40ed94ea713f7c8''iline' 在 6998 和 7000 之间的所有字典。 我知道交集方法有助于匹配字典值,但是当我想将一个值与 range 值匹配时,我该怎么做呢?

我做了什么:

def check_correspondence(obj, query):
    for _, value in obj.items():

        if value.keys() & query.keys():
            return True
        else: return False

我遍历提到的字典并应用 & 运算符。但是,此运算符似乎不适用于范围比较,只能用于严格相等。 当我尝试它时,我会收到一个TypeError: unhashable type: 'list'

【问题讨论】:

  • 您测试范围,而不是直接相等。你被困在哪里了? “告诉我如何解决这个编码问题”不是堆栈溢出问题。我们希望您做出诚实的尝试,然后然后就您的算法或技术提出一个具体的问题。请从intro tour 重复on topichow to ask
  • 哦,当然,抱歉。我将使用我已经编写的代码编辑问题。
  • 您的循环只计算一次,然后返回真或假。还有像if [condition]: return True; else: return False 这样的东西可以简化为return condition

标签: python python-3.x dictionary search intersection


【解决方案1】:

您无需检查所有密钥,只需检查 id 和 iline

注意,&and 在 python 中是不一样的。 &bit-wise operator

objs = {
    "id_1" : { 
        "_id" : "5cefddaae40ed94ea713f7c8", 
        "derived_from" : "5cefddaae40ed94ea713f7c7", 
        "epsg" : "32723", 
        "active" : True, 
        "name" : "DPA-Time", 
        "range_time_depth" : [ 4648.91338, 5641.545770000001 ], 
        "type" : "Polygon",
        "iline": 6998 
    },
    "id_2" : { 
        "_id" : "5cefddaae40ed94ea713f7c9", 
        "derived_from" : "5cefddaae40ed94ea713f7c7", 
        "epsg" : "32723", 
        "active" : True, 
        "name" : "DPA-Time", 
        "range_time_depth" : [ 4648.91338, 5641.545770000001 ], 
        "type" : "Polygon",
        "iline": 7002
    } 
}

query_ = {
    '_id': { '$in': ['5cefddaae40ed94ea713f7c8','5cefddaae40ed94ea713f7c9'] },
    'iline': {'$gte': 6998, '$lte': 7000}
}

def check_correspondence(obj, query):
    is_in = obj['_id'] in query['_id']['$in']
    is_iline = query['iline']['$lte'] >= obj['iline'] >= query['iline']['$gte']
    
    return is_in and is_iline

for obj_name, obj_ in objs.items():
    print(obj_name, check_correspondence(obj_, query_))
    
# id_1 True
# id_2 False - because 7002 > 7000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多