python - 对字典中的数组进行排序
问题描述
数组中的信息与我想要的“相反”顺序。理想情况下,它可以按数组中的日期进行排序,但我 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)] .... }
解决方案
你可以试试:
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>}
>>>
推荐阅读
- python - 考虑字段中的零值的字节字符串反序列化
- java - 无状态弹簧应用程序 - JSESSIONID 仍然生成
- jsp - 如何使用 wget 保存 JavaServer HTML 页面?
- kentico - Kentico 中的新页面未在 googlesitemap.xml 中列出
- r - 编写一个名为 steps() 的函数,它为任何 n 构建一个方形楼梯
- java - Android Studio/Java/XML 中的“未绑定前缀”是什么?
- python - python-docx 可以在导入文档时保留字体颜色和样式吗?
- linux - 使用 Bash 迭代计算斐波那契数
- kernel-module - 如何在 buildroot 中获取内核模块存档?
- mysql - 是否可以在视图中使用对称键?