python坐标值为文字,Python:如何通过递增X坐标值来对X和Y坐标的字典排序?

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]

}

解决方案

You can try this:

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

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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值