1

I have a nested linked list:

list_a = [[A, 12.1], [B, 15.6], [C, 9.8], [D, 12.1], [F, 96.3]]

I have sorted the list successfully using sorted(list_a), according to the second elements of the sub-lists. How do I get output A and D(first-elements of the list with second-smallest second-elements)?

jpp
  • 159,742
  • 34
  • 281
  • 339
Tanbir
  • 63
  • 1
  • 6

2 Answers2

1

A full sort is unnecessary here. You can use heap.nsmallest followed by a list comprehension:

from heapq import nsmallest
from operator import itemgetter

list_a = [['A', 12.1], ['B', 15.6], ['C', 9.8], ['D', 12.1], ['F', 96.3]]

second_largest_val = nsmallest(2, map(itemgetter(1), list_a))[1]
res = [key for key, val in list_a if val == second_largest_val]

# ['A', 'D']
jpp
  • 159,742
  • 34
  • 281
  • 339
0

You can use the following conditional list comprehension:

list_a = [['A', 12.1], ['B', 15.6], ['C', 9.8], ['D', 12.1], ['F', 96.3]]
sorted_a = sorted(list_a, key=lambda x: x[1])
[x for x, y in sorted_a if y == sorted_a[1][1]]
# ['A', 'D']

This does however check float objects for equality which is not ideal. So you might want to resort to using math.isclose which is available in Python >= 3.5:

from math import isclose
[x for x, y in sorted_a if isclose(y, sorted_a[1][1])]
# ['A', 'D']
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Could you please explain what does isclose(y, sorted_a[1][1]) do? More specifically, does sorted_a[1][1] refer to the second element of second sub_list specifically? If so, how do we encounter more than one least second-elements.. – Tanbir Nov 02 '18 at 09:47
  • I linked the docs to `isclose` in the answer. Since floats suffer from precision issues, this function allows you to assert approximate equality. `sorted_a[1][1] ` does refer to the second element of second sub_list (`12.1`) and the comprehension collects all first elements that this very second element. – user2390182 Nov 02 '18 at 10:00