2016-06-28 71 views
2

我試圖找到字典中匹配值的鍵。但要獲得任何有效的匹配,我需要截斷列表中的值。截斷字典列表值

我想截斷十分之一點(例如「2.21」到「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"。但我不確定是否需要先解析每個值列表,然後進行更改,然後繼續。如果我能夠對比較本身進行改變,那將是理想的。

回答

2

您可以使用列表zip和比較值,但你應該設定一個公差tol用於從兩個列表的一對值將被認爲是相同的:

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')] 

如果您的列表長度將始終相同,您可以刪除不匹配長度被跳過的部分。

+0

我認爲它需要一個元組列表,這並不是真的很重要。 – RoadRunner

+0

@RoadRunner好眼睛,謝謝! –

+1

耶沒有憂慮:),順便說一句,你的解決方案是雄偉! – RoadRunner

3
d = {'green': [3.11, 4.12, 5.2]} 

>>> map(int, d['green']) 
[3, 4, 5] 

您需要映射列表項爲整數你比較

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

之前,我假設你想四捨五入。如果您想要舍入到最接近的整數使用round代替int

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: 
     dict1[key1] = [int(i) for i in dict1[key1]] 
     dict2[key2] = [int(i) for i in dict2[key2]] 

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

輸出:

[('blue', 'yellow'), ('orange', 'green')] 

我希望這有助於:)

2

如果你關心的只是截斷,而不是實際的四捨五入,你可以將這些值轉換爲一個字符串並切掉多餘的部分:

for key1 in dict1: 
    for key2 in dict2: 
     # I'm pulling these values out so you can look at them: 
     a = str(dict1[key1]) 
     b = str(dict1[key2]) 
     # find the decimal and slice it off 
     if a[:a.index('.')] == b[:b.index('.')]: 
      matches.append((key1, key2)) 

如果你想真正全面,使用內置round(float, digits)https://docs.python.org/2/library/functions.html):

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

(另外,看你的凹痕!)

+1

你可以使用int()... – Neo

+0

謝謝!這就是爲什麼joel的map()'答案是我發佈的第一個用例的最佳方法,而Moses的答案符合'不捨入舍入到1的小數'規範。不過,我認爲這是經過編輯的,或者當我第一次閱讀這個問題時我錯過了。 – Clay