sorting list of objects in Python
本问题已经有最佳答案,请猛点这里访问。
在python中,我使用这个模块将一个
1 2 3 4 | configdict = ConvertXmlToDict('tasks.xml') for task in configdict['osmo_tasks']['tasks_entries']['entry']: print task['id'], task['due_date'], task['summary'] |
上面的代码将把
1 2 3 | 1 736366 summary 2 735444 another summary 5 735796 blah |
如何打印按
这是一个示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <?xml version="1.0" encoding="utf-8"?> <osmo_tasks version="000212"> <category_entries/> <tasks_entries> <entry> <id>1</id> <status>1</status> <due_date>736366</due_date> <due_time>53100</due_time> <summary>summary</summary> </entry> <entry> <id>2</id> <status>1</status> <due_date>735444</due_date> <due_time>55800</due_time> <summary>another summary</summary> </entry> <entry> <id>5</id> <status>0</status> <due_date>735796</due_date> <due_time>55800</due_time> <summary>blah</summary> </entry> </tasks_entries> </osmo_tasks> |
尝试
SytEdTest.Py
1 2 3 4 5 6 7 8 9 10 11 12 13 | configdict = { 'tasks': { 'entries': [ { 'id': 1, 'date': 736366 }, { 'id': 2, 'date': 735444 }, { 'id': 3, 'date': 735796 } ] } } tasks = sorted([ t for t in configdict['tasks']['entries'] ], key=lambda task: task['date']) print repr(tasks) |
结果:
1 | [{'date': 735444, 'id': 2}, {'date': 735796, 'id': 3}, {'date': 736366, 'id': 1}] |
使用
参考文献
类似:
1 | sorted(configdict,key=lambda x: x['due_date']) |