0

I am trying to find the second minimum value in a nested list, where every sublist contains a name and a float value.

I need help with comparing the associated float values if there are any duplicate values.

if __name__ == '__main__':
    n = int(input())
    list = []
    for _ in range(n):
        name = input()
        score = float(input())
        list.append([name,score])


listsort = sorted(list,key = lambda x:x[1])
newlist = listsort[1:2]
#if listsort[] 
newlist.sort()
print(newlist)

it works fine without duplicate values.

Input : 
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Output : [['Berry', 37.21] ['Harry', 37.21]]

killgore_bot
  • 61
  • 1
  • 8
  • So you need help making this work when there are duplicates? How should it behave under such circumstances? – Scott Hunter Jul 12 '19 at 15:43
  • As I understand correctly, do you need to return two values in this case, `Berry` and `Tina`? – Andrej Kesely Jul 12 '19 at 15:44
  • Consider in the input the user gives XYZ, 37.21, then the code should return both XYZ and Berry – killgore_bot Jul 12 '19 at 15:46
  • Yeah two values but with the same number here Berry - 37.21 and Tina - 37.2 so just Berry – killgore_bot Jul 12 '19 at 15:48
  • You need to make a [mcve] and [edit] it in to the question. For example the input process is irrelevant; just give us a value for `list`. BTW, `list` is a bad name since it overwrites the `list` builtin. – wjandrea Jul 12 '19 at 15:49
  • Please [edit] your question to add a *clear* example input and your desired output from that. – heemayl Jul 12 '19 at 15:49

1 Answers1

2

Adapting your code, we can enumerate over the list and check if the float value is equal to listsort[1][1] (the 2nd smallest value). If so, return the person and float value.

if __name__ == '__main__':
    n = int(input())
    list = []
    for _ in range(n):
        name = input()
        score = float(input())
        list.append([name,score])


listsort = sorted(list,key = lambda x:x[1])
print([listsort[i] for i, x in enumerate(listsort) if x[1] == listsort[1][1]])

Input:

4
Tom
1
Jeff
2
Bob
2
Henry
3

Result:

[['Jeff', 2.0], ['Bob', 2.0]]
TomNash
  • 3,147
  • 2
  • 21
  • 57