我正在尝试在 Python 中映射字典和列表之间的值。 我正在尝试计算在图像中找到的物体的数量: 例如我发现: 方格:3 矩形:4 椭圆形=2 三角形=1
现在我将它们全部按降序附加到列表中。
列表变为:[4,3,2,1]
现在我想说列表中的“4”对应于“矩形”, “2”对应于“椭圆形” 我正在尝试使用字典,但很困难。
由于我对多个图像执行此操作,因此输出会有所不同。 例如,下图给出了结果:
方格:4 矩形:3 椭圆形=1 三角形=2
现在列表变为 [4,3,1,2]
因此,它应该将“4”映射到正方形而不是矩形
最佳答案
我会使用字典:
# 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
对于细心的读者来说,字典根本没有必要——但是我想,还有更多我们不知道的目标,而字典在哪些方面最有意义。
关于python - Python 中列表和字典的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36804668/