截断字典列表值 [英] Truncate dictionary list values

查看:149
本文介绍了截断字典列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在字典中找到匹配值的键.但是要获得任何有效的匹配,我都需要截断列表中的值.

I'm trying to find the keys for the matching values in a dictionary. But to get any kind of valid match I need to truncate the values in the lists.

我想将十分之一的位置截短(例如,从"2.21"到"2.2").

I want to truncate down the the tenths spot (e.g. "2.21" to "2.2").

dict1 = {'red':[1.98,2.95,3.83],'blue':[2.21,3.23,4.2333],'orange':[3.14,4.1,5.22]}

dict2 = {'green':[3.11,4.12,5.2],'yellow':[2.2,3.2,4.2],'red':[5,2,6]}

matches = []
for key1 in dict1:
    for key2 in dict2:
        if dict1[key1] == dict2[key2]:
            matches.append((key1, key2))

print(matches)

我试图获取"green""orange"应该匹配,以及"blue""yellow".但是我不确定是否需要首先解析每个值列表,进行更改,然后继续.如果我可以在比较本身中进行更改,那将是理想的选择.

I'm trying to get "green" and "orange" should be a match, as well as "blue" and "yellow". But I'm not sure if I need to parse through each value list first, make the changes, and then continue. If I could make the changes in the comparison itself that would be ideal.

推荐答案

您可以在列表上使用zip并比较值,但是您应该设置一个容差tol,两个列表中的一对值将作为认为相同:

You can use zip on the lists and compare values, but you should set a tolerance tol for which a pair of values from two list will be considered the same:

dict1 = {'red':[1.98,2.95,3.83],'blue':[2.21,3.23,4.2333],'orange':[3.14,4.1,5.22]}
dict2 = {'green':[3.11,4.12,5.2],'yellow':[2.2,3.2,4.2],'red':[5,2,6]}

matches = []
tol = 0.1 # change the tolerance to make comparison more/less strict
for k1 in dict1:
    for k2 in dict2:
        if len(dict1[k1]) != len(dict2[k2]):
            continue
        if all(abs(i-j) < tol for i, j in zip(dict1[k1], dict2[k2])):
            matches.append((k1, k2))

print(matches)
# [('blue', 'yellow'), ('orange', 'green')]

如果列表长度始终相同,则可以删除跳过不匹配长度的部分.

If your list lengths will always be the same, you can remove the part where non matching lengths are skipped.

这篇关于截断字典列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆