首页 > 解决方案 > 对字典中的数组进行排序

问题描述

数组中的信息与我想要的“相反”顺序。理想情况下,它可以按数组中的日期进行排序,但我 100% 确定只需颠倒顺序即可。通过使用这样的东西:

sorted(Dictionary[self], key=lambda i: i[1][0], reverse=True)

我知道上面只是将数组本身排序为倒序,而不是将数组内的数据排序为倒序。像这样使用字典(所有项目都是文件名)

Dictionary = {'a':[XPJulianDay(Timefurthestinpastfromnow), ... XPJulianDay(timeclosest2currnttime)], 'b':[RQJulianDay(Timefurthestinpastfromnow), ... RQJulianDay(timeclosest2currnttime)], 'c':[WSJulianDay(Timefurthestinpastfromnow), ... WSJulianDay(timeclosest2currnttime)] ..... (9 different ones total) }

变成这个

Dictionary = {'a':[XPJulianDay(timeclosest2currnttime), ... XPJulianDay(Timefurthestinpastfromnow)], 'b':[RQJulianDay(timeclosest2currnttime), ... RQJulianDay(Timefurthestinpastfromnow)], 'c':[WSJulianDay(timeclosest2currnttime), ... WSJulianDay(Timefurthestinpastfromnow)] .... }

标签: pythonpython-3.x

解决方案


你可以试试:

Dictionary.update({ k: sorted(v) for k, v in Dictionary.items() })

它使用自己的键和排序的值更新字典。

例子:

>>> Dictionary = {"a": [7,6,1,2], "b": [8,0,2,5] }
>>> Dictionary.update({ k: sorted(v) for k, v in Dictionary.items() })
>>> Dictionary
{'a': [1, 2, 6, 7], 'b': [0, 2, 5, 8]}
>>> 

请注意,为调用.update()使用字典推导创建了一个新字典。

如果需要,您可以替换sorted()reversed(); 但reversed()返回一个迭代器,所以如果你想要一个列表,你需要调用它list()(如果可以的话,最好保留迭代器)。

示例reversed

>>> Dictionary = {"a": [7,6,1,2], "b": [8,0,2,5] } ; Dictionary.update({ k: reversed(v) for k, v in Dictionary.items() })
>>> Dictionary
{'a': <list_reverseiterator object at 0x7f537a0b3a10>, 'b': <list_reverseiterator object at 0x7f537a0b39d0>}
>>>

推荐阅读