简体   繁体   English

什么是重新排序由dicts组成的列表的Pythonic方法?

[英]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.

相关问题 Pythonic排序列表的方式 - Pythonic way of sorting a list 检查列表是否已排序的 Pythonic 方法 - Pythonic way to check if a list is sorted or not 假设我在Python中有一个列表。 按部分将其随机化的最有效的Python方法是什么? - Suppose I had a list in Python. What's the most pythonic and efficient way to randomize it by sections? 用Python的方式对具有多个属性的列表进行排序的方式是什么,从而第一个被反向排序而第二个则没有? - What is the pythonic way to sort a list with multiple attributes, such that the first is sorted reversely but the second is not? 在列表中找到最大值(和索引)的Python方法 - Pythonic way to find highest values (and indexes) in list 从中间对列表进行排序的最 Pythonic 方式? - Most Pythonic way to sort a list from middle? 用于对逗号分隔数列表进行排序的Pythonic方法 - Pythonic Way to Sort a List of Comma Separated Numbers 按字段名称对命名元组列表进行排序的 Pythonic 方法 - Pythonic way to sorting list of namedtuples by field name 根据排序另一个名为?的列表产生的隐含重新排序重新排序一个列表的过程是什么? - What is the process of reordering one list based on the implied reordering resulting from sorting another list called? pythonic方法按内部列表的最后一项对列表进行排序 - pythonic way to sort a list of lists by the last item of the inner list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM