繁体   English   中英

Python使用Lambda排序列表或由多个键决定的字典

[英]Python using lambda sort list or dicts by multiple keys

这是我的字典列表:

l = [{'a': 2, 'c': 1, 'b': 3}, 
     {'a': 2, 'c': 3, 'b': 1}, 
     {'a': 1, 'c': 2, 'b': 3},
     {'a': 1, 'c': 3, 'b': 2}, 
     {'a': 2, 'c': 5, 'b': 3}]

现在,我想按用户提供的键和顺序对列表进行排序。 例如:

keys = ['a', 'c', 'b']
orders = [1, -1, 1]

我试图在sort()方法中使用lambda,但是它以一种奇怪的方式失败了:

>>> l.sort(key=lambda x: (order * x[key] for (key, order) in zip(keys, orders)))
>>> l
[{'a': 2, 'c': 5, 'b': 3},
 {'a': 1, 'c': 3, 'b': 2},
 {'a': 1, 'c': 2, 'b': 3},
 {'a': 2, 'c': 3, 'b': 1},
 {'a': 2, 'c': 1, 'b': 3}]

有人知道如何解决吗?

你快到了; 您的lambda会生成生成器表达式,而它们恰好由其内存地址排序(在Python 2中),并生成TypeError: '<' not supported between instances of 'generator' and 'generator'在Python 3 TypeError: '<' not supported between instances of 'generator' and 'generator'异常TypeError: '<' not supported between instances of 'generator' and 'generator'

改用列表理解:

l.sort(key=lambda x: [order * x[key] for (key, order) in zip(keys, orders)])

演示:

>>> l = [{'a': 1, 'c': 2, 'b': 3},
...      {'a': 1, 'c': 3, 'b': 2},
...      {'a': 2, 'c': 1, 'b': 3},
...      {'a': 2, 'c': 5, 'b': 3},
...      {'a': 2, 'c': 3, 'b': 1}]
>>> keys = ['a', 'c', 'b']
>>> orders = [1, -1, 1]
>>> l.sort(key=lambda x: [order * x[key] for (key, order) in zip(keys, orders)])
>>> from pprint import pprint
>>> pprint(l)
[{'a': 1, 'b': 2, 'c': 3},
 {'a': 1, 'b': 3, 'c': 2},
 {'a': 2, 'b': 3, 'c': 5},
 {'a': 2, 'b': 1, 'c': 3},
 {'a': 2, 'b': 3, 'c': 1}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM