Mat*_*teo 2 python sorting lambda
我有一个列表,其元素是带有值和类型字段的字典,即:
my_list = [{'val':5, 'type':0},{'val':6, 'type':2},{'val':2, 'type':1},{'val':9, 'type':0}]
Run Code Online (Sandbox Code Playgroud)
我想基于该type字段以降序对列表进行排序,并基于该字段在每种类型中对列表进行排序value,并获得一个具有相应排序索引和排序矢量的矢量。
我知道如何使用lambda函数针对单个条件执行此操作,即:
sorted_list = sorted(my_list, key=lambda k: k['type'], reverse=True)
Run Code Online (Sandbox Code Playgroud)
但是如何将其扩展到多个条件?
所需输出:
sorted_list = [{'val':6, 'type':2},{'val':2, 'type':1},{'val':9, 'type':0},{'val':5, 'type':0}]
sorted_idxs = [1, 2, 3, 0]`, such that `[my_list[k] for k in sorted_idxs]==sorted_list
Run Code Online (Sandbox Code Playgroud)
如果key返回一个元组,sorted则在排序时将按顺序考虑它们:
In [3]: sorted(my_list, key=lambda k: (k['type'], k['val']), reverse=True)
Out[3]:
[{'type': 2, 'val': 6},
{'type': 1, 'val': 2},
{'type': 0, 'val': 9},
{'type': 0, 'val': 5}]
Run Code Online (Sandbox Code Playgroud)
如果需要索引,也可以enumerate在其中添加:
In [7]: sorted(enumerate(my_list), key=lambda k: (k[1]['type'], k[1]['val']), reverse=True)
Out[7]:
[(1, {'type': 2, 'val': 6}),
(2, {'type': 1, 'val': 2}),
(3, {'type': 0, 'val': 9}),
(0, {'type': 0, 'val': 5})]
In [8]: [k for k, v in sorted(enumerate(my_list), key=lambda k: (k[1]['type'], k[1]['val']), reverse=True)]
Out[8]: [1, 2, 3, 0]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2329 次 |
| 最近记录: |