Reputation: 686
I have a list of lists, where each sublist is a list of objects. The task is to return a list of top n sublists in the descending order of their length.
Illustration:
[[{},{},{},{}],[{},{},{}],[{},{}],[{}],[]]
For above, I want to return a list of top 3 sublists as per length, which is
[[{},{},{},{}],[{},{},{}],[{},{}]]
as the sublists have largest length 3,2,1 respectively from the list.
Upvotes: 2
Views: 168
Reputation: 536
>>> a = [[{},{},{},{}],[{},{},{}],[{},{}],[{}],[]]
>>> sorted(a, key=len, reverse=True)
[[{}, {}, {}, {}], [{}, {}, {}], [{}, {}], [{}], []]
You can always choose select top k
after splicing the result of sorted
by sorted(a, key=len, reverse=True)[0:k]
.
Main observation to note is argument key
, which can also accept any crazy lambda
function too.
Upvotes: 2
Reputation: 69725
You have two possible options, let's say:
l = [[{},{},{},{}],[{},{},{}],[{},{}],[{}],[]]
You can produce a completely new list and take the desired 3 elements:
sorted(l, key=len, reverse=True)[:3]
Or, you can sort your original list and them take the first 3 elements:
l.sort(key=len, reverse=True)
l[:3]
In terms of performance, the second option seems faster:
In [1]: %timeit sorted(l, key=len, reverse=True)[:3]
1.9 µs ± 28.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [2]: %%timeit
...: l.sort(key=len, reverse=True)
...: l[:3]
...:
1.22 µs ± 33.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Upvotes: 4