簡體   English   中英

在python列表中找到最接近的值對

[英]find closest value pair in python list

我有這樣的字典:

d = {'ID_1':[(10, 20), (40, 60), (125, 200)], 'ID_2': [(75, 100), (250, 300)]}

以及職位和ID:

pos = 70
IDed = ID_1
output = (40, 60)

pos = 90
IDed = ID_2
expected output = (75, 100)

pos = 39
IDed = ID_1
expected output = (40, 60)

我想在最接近test pos的列表中找到值對。

我已經在下面嘗試過了:

if IDed in d:
    y = d[IDed]
    closest = min(y, key=lambda x:abs(x-pos))

這不起作用,因為它不是具有單個值的列表。 還有另一種方法可以使用類似的方法來執行此操作。 如果沒有,我可以通過在列表中建立索引並計算每個值對之間的距離找到解決問題的方法。 但是,我認為這不會非常有效。

你真的很親近 波紋管是一個可行的解決方案。

d = {'ID_1': [(10, 20), (40, 60), (125, 200)], 'ID_2': [(75, 100), (250, 300)]}    
pos = 70
IDed = 'ID_1'

closest = min(d[IDed], key=lambda x: min(abs(y - pos) for y in x)) if IDed in d else None    
print(closest)
# (40, 60)

代碼的問題在於,您嘗試執行x - pos ,而x是整個元組(例如(40,60)),而pos是整數目標值。


如果需要多次運行,可以考慮將其包裝在函數中以避免代碼重復。

def find_nearest(point_dict, id, stigma):
    try:
        return min(point_dict[id], key=lambda x: min(abs(w - stigma) for w in x))
    except:
        return None

d = {'ID_1': [(10, 20), (40, 60), (125, 200)], 'ID_2': [(75, 100), (250, 300)]}
print(find_nearest(d, 'ID_1', 70))
# (40, 60)

請注意,在類似d = {'ID_1': [(10, 20), (40, 69), (71, 200)], ...}情況下,術語在嵌套在初始詞典中的列表中出現的順序很重要d = {'ID_1': [(10, 20), (40, 69), (71, 200)], ...} 術語6971與給定的目標70等距,但是代碼返回(40, 69)因為它首先找到了那個。

我認為您想找到具有pos值平均數最接近的那對夫婦...因此,這就是答案:

d = {'ID_1':[(10, 20), (40, 60), (125, 200)], 'ID_2': [(75, 100), (250, 300)]}
pos = 70

closest = (0, 0)

IDed = "ID_1"

for i in d.items():
    if IDed == i[0]:
        for x in i[1]:
            avg = (x[0]+x[1])/2
            avg_closest = (closest[0]+closest[1])/2
            if abs(pos-avg) < abs(pos-avg_closest):
                closest = x

print closest

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM