2016-04-22 91 views
1

我想在Python中的字典和列表之間映射值。 我試圖計數我在圖像中找到的對象的數目: 例如我發現: 正方形:3個 矩形:4 橢圓= 2 三角= 1在Python中映射列表和字典

現在我追加所有這些給按降序排列。

列表變爲:[4,3,2,1]

現在我想在某種程度上說是「4」列表中的對應於「矩形」, 「2」對應於「橢圓形」 我我試圖使用字典,但掙扎。

因爲,我爲多個圖像做這個,輸出會有所不同。 例如,下一圖像給出了結果:

正方形:4個 矩形:3 橢圓= 1 三角= 2

現在列表變成[4,3,1,2]

因此,它應該映射 '4' 的Square,而不是矩形

+1

你能澄清你到底在問什麼嗎?你說你正在將字典的值映射到一個列表,所以你在那個時候丟失了密鑰。但是你說你想再次使用這些鍵。你爲什麼需要這個清單? –

+0

您應該反轉鍵值對,並真正質疑您的數據結構。 如果你有一個'mydict = {4:'Rectangles'}'的字典,那麼'mydict [4]'會給你''矩形''。 但是爲什麼在你只需要一本字典時使用它們呢?你似乎有不必要的物體。 –

+0

您可能想要使用「Counter」及其「most_common」方法。 https://docs.python.org/2/library/collections.html#collections.Counter.most_common –

回答

1

我會使用一個字典:

# Squares:3 Rectangles:4 Oval=2 Triangle=1 

shapes = {} 
shapes["Square"] = 3 
shapes["Rectangle"] = 4 
shapes["Oval"]  = 2 
shapes["Triangle"] = 1 

print(shapes)    # {'Square': 3, 'Oval': 2, 'Triangle': 1, 'Rectangle': 4} 

# Sort list of key,value pairs in descending order 
pairs = sorted(shapes.items(), key=lambda pair: pair[1], reverse=True) 
print(pairs)    # [('Rectangle', 4), ('Square', 3), ('Oval', 2), ('Triangle', 1)] 

# Get your list, in descending order 
vals = [v for k,v in pairs] 
print(vals)     # [4, 3, 2, 1] 

# Get the keys of that list, in the same order 
keys = [k for k,v in pairs] # ['Rectangle', 'Square', 'Oval', 'Triangle'] 
print(keys) 

輸出:

{'Square': 3, 'Oval': 2, 'Triangle': 1, 'Rectangle': 4}   # shapes 
[('Rectangle', 4), ('Square', 3), ('Oval', 2), ('Triangle', 1)] # pairs 
[4, 3, 2, 1]              # vals 
['Rectangle', 'Square', 'Oval', 'Triangle']      # keys 

對於細心的讀者,字典是沒有必要的 - 但我想有更多的,我們不知道的目標,其中一本字典將使最有意義。

+0

謝謝。得到它的工作 –