使用math.isclose比较python中的字典,字典理解中如何实现

Use math.isclose to compare dictionaries in python, how to implement in dictionary comprehension

我正在使用 math.isclose 在字典中匹配 lat/long 个位置,彼此之间的距离在 0.05 以内。

示例字典 A:


{"LATITUDE": 29.53, 
 "LONGITUDE": 105.73, 
 }

示例 dictB:


{"LATITUDE": 29.93, 
 "LONGITUDE": 106.13,

 }

对于我的代码,我编写了以下字典理解:

matching_keys = dictA.keys() & dictB.keys()
z = {k: dictA[k] == dictB[k] for k in matching_keys}
print(z)
spiredictval += 1
index += 1

#matches true on lat + long + minute (timestamp)

if (z['latitude'] == True and z['longitude'] == True):
    trueMatches += 1
    #using kwargs, merge matches to one dictionary
    dict3 = {**dictA , **dictB}
    jsonoutput_list.append(dict3)
    print(dict3)

我不确定如何将 math.isclose(float(a), float(b), abs_tol=0.05) 添加到字典理解中。特别地,其中 Z = {k: dictA[k] == dictB[k] for k in matching_keys}。

如果您想对某些键应用不同的比较方法,您需要在值表达式中进行测试:

z = {k: (
    math.isclose(float(dictA[k]), float(dictB[k]), abs_tol=0.05)
    if k in {'latitude', 'longitude'}
    else dictA[k] == dictB[k]) for k in matching_keys
}

这相当冗长,因此您可能希望使用分派字典来存储每个键名的测试:

from operator import eq

geo_close = lambda a, b: math.isclose(float(a), float(b), abs_tol=0.05)
comparisons = {
    'longitude': geo_close,
    'latitude': geo_close,
}
default_comp = eq
z = {k: comparisons.get(k, default_comp)(dictA[k], dictB[k]) for k in matching_keys}

comparisons字典将键名映射到比较函数,如果键名不在字典中,则使用operator.eq()代替。该函数的作用与 ==.

完全相同