[英]What is the Pythonic way of reordering a list consisting of dicts?
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? 那么我如何在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. 我想出了使用sort并创建一个lambda函数来对它进行排序。 Is this a good way? 这是一个好方法吗? And is it efficient? 它有效吗?
list.sort(cmp=lambda x,y: cmp(x['nr'], y['nr']))
No, using cmp=
is not efficient. 不,使用cmp=
效率不高。 Use key=
instead. 使用key=
代替。 Like so: 像这样:
sorted(list, key=lambda x: x['nr'])
The reason is simple: cmp
compares two objects. 原因很简单: cmp
比较两个对象。 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. 但是key
不是这种情况,因此排序长列表要快得多。
But the main reason to use key
instead of cmp
is that it's much easier to use. 但是使用key
而不是cmp
主要原因是它更容易使用。
Also, sorted
() has a benefit over .sort()
, it can take any iterable, while .sort()
inly works on lists. 此外, sorted
()比.sort()
有好处,它可以采用任何可迭代,而.sort()
可以在列表上运行。
mylist.sort(key=operator.itemgetter('nr'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.