0

This is the format of nested list:

[['A', 0],['B', 0], ['V', 0], ['D', 0], ['E', 0], ['F', 0], ['G', 1], ['H', 1], ['I', 1], ['J', 3], ['K', 0]]

I have nested list in such format, I need to get top 3 nested lists which have max nested list integer value such as my result should be ['J', 3] , ['I', 1] , ['H', 1] I have tried to use the nested loop where i can get the max integer but struck at getting the string of those max 3 integers

Can someone please help me out here

RoadRunner
  • 25,803
  • 6
  • 42
  • 75

2 Answers2

2

I would do this:

First order list by number in nested list. In lambda function I return the value that has to be used for ordenation (2nd element of nested list):

a = [['A', 0],['B', 0], ['V', 0], ['D', 0], ['E', 0], ['F', 0], ['G', 1], ['H', 1], ['I', 1], ['J', 3], ['K', 0]]

sorted_list = sorted(a, key=lambda n: n[1], reverse=True)
# [['J', 3], ['G', 1], ['H', 1], ['I', 1], ['A', 0], ['B', 0], ['V', 0], ['D', 0], ['E', 0], ['F', 0], ['K', 0]]

With this I could slice 3 first elements:

sorted_list = sorted_list[:3]
# [['J', 3], ['G', 1], ['H', 1]]

And finally get a list with only letter (string):

[l[0] for l in sorted_list]
# ['J', 'G', 'H']

All at once:

[n[0] for n in sorted(a, key=lambda n: n[1], reverse=True)[:3]]
user2390182
  • 72,016
  • 6
  • 67
  • 89
salpreh
  • 190
  • 2
  • 6
1

Adding to @salpreh's answer, you could also use operator.itemgetter with key for a slight speed increase:

from operator import itemgetter

a = [['A', 0],['B', 0], ['V', 0], ['D', 0], ['E', 0], ['F', 0], ['G', 1], ['H', 1], ['I', 1], ['J', 3], ['K', 0]]

print(sorted(a, key=itemgetter(0), reverse=True))
# [['V', 0], ['K', 0], ['J', 3], ['I', 1], ['H', 1], ['G', 1], ['F', 0], ['E', 0], ['D', 0], ['B', 0], ['A', 0]]

This question offers some performance stats between the two.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75