对由字典组成的列表进行重新排序的 Pythonic 方法是什么?
我有以下列表:
list = [{'nr' : 2, 'name': 'streamname'}, {'nr' : 3,'name': 'streamname'}, {'nr' : 1, 'name': 'streamname'}]
那么我如何在 python 中以有效的方式将其重新排序为这样?
list = [{'nr' : 1, 'name': 'streamname'}, {'nr' : 2,'name': 'streamname'}, {'nr' : 3, 'name': 'streamname'}]
我想出了使用 sort 并创建一个 lambda 函数来对其进行排序。这是个好办法吗?它有效率吗?
list.sort(cmp=lambda x,y: cmp(x['nr'], y['nr']))
I have the the following list:
list = [{'nr' : 2, 'name': 'streamname'}, {'nr' : 3,'name': 'streamname'}, {'nr' : 1, 'name': 'streamname'}]
So how would I reorder it to become like this in an efficient way in python?
list = [{'nr' : 1, 'name': 'streamname'}, {'nr' : 2,'name': 'streamname'}, {'nr' : 3, 'name': 'streamname'}]
I came up with using sort and creating a lambda function to sort it. Is this a good way? And is it efficient?
list.sort(cmp=lambda x,y: cmp(x['nr'], y['nr']))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,使用
cmp=
效率不高。请改用key=
。就像这样:原因很简单:
cmp
比较两个对象。如果列表很长,则需要比较两个对象的多种组合,因此两倍长的列表需要两倍多的时间来排序。但对于
key
来说,情况并非如此,因此对长列表进行排序要快得多。但使用
key
而不是cmp
的主要原因是它更容易使用。此外,
sorted
() 比.sort()
有一个好处,它可以接受任何可迭代对象,而.sort()
只适用于列表。No, using
cmp=
is not efficient. Usekey=
instead. Like so:The reason is simple:
cmp
compares two objects. If your list is long, there are many combinations of two objects you can have to compare, so a list that is twice as long takes much more than twice as long to sort.But with
key
this is not the case and sorting long lists are hence much faster.But the main reason to use
key
instead ofcmp
is that it's much easier to use.Also,
sorted
() has a benefit over.sort()
, it can take any iterable, while.sort()
inly works on lists.