Python:如何通过递增X坐标值来对X和Y坐标的字典进行排序? [英] Python: How to sort a dictionary of X and Y coordinates by ascending X coordinate value?

查看:487
本文介绍了Python:如何通过递增X坐标值来对X和Y坐标的字典进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要根据其X坐标以升序对以下字典进行排序,以便我可以通过颜色排列(RGB以不同顺序)来识别信标".我一直试图像列表一样对它进行排序,但是效果不是很好.在此先感谢:)

I have the following dictionary that I would like to sort based on their X coordinate in ascending fashion so that I can identify the "beacon" by the color arrangement (RGB in different orders). I keep trying to sort it like a list but that's not working out too well. Thanks in advance :)

Beacon2 = {
    'r': [998.9282836914062, 367.3825378417969],
    'b': [985.82373046875, 339.2225646972656], 
    'g': [969.539794921875, 369.2041931152344]
}

对于此特定词典,预期结果为

For this specific dictionary the expected result is

sortedBeacon = {
    'g': [969.539794921875, 369.2041931152344], 
    'b': [985.82373046875, 339.2225646972656],
    'r': [998.9282836914062, 367.3825378417969]
} 

推荐答案

您可以尝试以下操作:

from collections import OrderedDict

Beacon2 = {'r': [998.9282836914062, 367.3825378417969], 'b':
[985.82373046875, 339.2225646972656], 'g': [969.539794921875, 369.2041931152344]}

sorted_beacons = sorted(Beacon2.items(), key = lambda x: x[1][0])

>>> print(OrderedDict(sorted_beacons))
OrderedDict([('g', [969.539794921875, 369.2041931152344]), ('b', [985.82373046875, 339.2225646972656]), ('r', [998.9282836914062, 367.3825378417969])])

首先在其中对来自Beacon2.items()的元组列表进行排序,并使用位于每个元组[1][0]的X坐标上的排序键.

Where you first sort the list of tuples from Beacon2.items(), with a sorting key applied on the X coordinate located at [1][0] of each tuple.

请注意,您需要包装 OrderedDict 根据您的结果来保留字典的顺序.

Note that you need to wrap an OrderedDict to your result to preserve order of the dictionary.

这篇关于Python:如何通过递增X坐标值来对X和Y坐标的字典进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆