开发者

What is the Pythonic way of reordering a list consisting of dicts?

开发者 https://www.devze.com 2023-02-03 22:52 出处:网络
I have the the following list: list = [{\'nr\' : 2, \'name\': \'streamname\'}, {\'nr\' : 3,\'name\': \'streamname\'}, {\'nr\' : 1, \'name\': \'streamname\'}]

I have the the following list:

list = [{'nr' : 2, 'name': 'streamname'}, {'nr' : 3,'name': 'streamname'}, {'nr' : 1, 'name': 'streamname'}]

So ho开发者_Python百科w 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']))


No, using cmp= is not efficient. Use key= instead. Like so:

sorted(list, key=lambda x: x['nr'])

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 of cmp 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.


mylist.sort(key=operator.itemgetter('nr'))
0

精彩评论

暂无评论...
验证码 换一张
取 消