将排序字典转换为列表
我有这个:
dictionary = { (month, year) : [int, int, int] }
我想要得到一个按月份和年份排序的元组或列表的列表:
#example info
list = [(8,2010,2,5,3),(1,2011,6,7,8)...]
我试了好几次,但就是找不到解决办法。
谢谢你的帮助。
3 个回答
0
这是一种非常简洁的方法来实现你所要求的功能。
l = [(m, y) + tuple(d[(y, m)]) for y, m in sorted(d)]
0
像这样应该就能解决问题:
>>> d = { (8, 2010) : [2,5,3], (1, 2011) : [6,7,8], (6, 2010) : [11,12,13] }
>>> sorted((i for i in d.iteritems()), key=lambda x: (x[0][1], x[0][0]))
[((6, 2010), [11, 12, 13]), ((8, 2010), [2, 5, 3]), ((1, 2011), [6, 7, 8])]
(假设这个函数是先按年份排序,然后再按月份排序。)
可以看看Alex Martelli的更好答案,里面讲了如何使用itemgetter
来解决这个问题。
5
不要用内置名称作为你的标识符——这是个很糟糕的做法,没有任何好处,最终会让你遇到一些奇怪的问题。所以我把结果叫做 thelist
(这是一个随意的、简单的、完全可以接受的标识符),而不是 list
(这会遮盖掉一个内置的名称)。
import operator
thelist = sorted((my + tuple(v) for my, v in dictionary.iteritems()),
key = operator.itemgetter(1, 0))