在Python中映射列表和字典
问题描述:
我想在Python中的字典和列表之间映射值。 我试图计数我在图像中找到的对象的数目: 例如我发现: 正方形:3个 矩形:4 椭圆= 2 三角= 1在Python中映射列表和字典
现在我追加所有这些给按降序排列。
列表变为:[4,3,2,1]
现在我想在某种程度上说是“4”列表中的对应于“矩形”, “2”对应于“椭圆形” 我我试图使用字典,但挣扎。
因为,我为多个图像做这个,输出会有所不同。 例如,下一图像给出了结果:
正方形:4个 矩形:3 椭圆= 1 三角= 2
现在列表变成[4,3,1,2]
因此,它应该映射 '4' 的Square,而不是矩形
答
我会使用一个字典:
# 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
谢谢。得到它的工作 –
你能澄清你到底在问什么吗?你说你正在将字典的值映射到一个列表,所以你在那个时候丢失了密钥。但是你说你想再次使用这些键。你为什么需要这个清单? –
您应该反转键值对,并真正质疑您的数据结构。 如果你有一个'mydict = {4:'Rectangles'}'的字典,那么'mydict [4]'会给你''矩形''。 但是为什么在你只需要一本字典时使用它们呢?你似乎有不必要的物体。 –
您可能想要使用“Counter”及其“most_common”方法。 https://docs.python.org/2/library/collections.html#collections.Counter.most_common –