Home > Enterprise >  python nested list sort based on 2nd value of the list is not working properly when it has value 10
python nested list sort based on 2nd value of the list is not working properly when it has value 10

Time:12-03

here is my code for hackerrank nested list problem in python problem link:https://www.hackerrank.com/challenges/nested-list/problem?isFullScreen=true

code:

def sort(sub_li):
    return(sorted(sub_li, key = lambda x: x[1]))
    
if __name__ == '__main__':
    x=int(input ())
    stu=[]
    record=[]
    for i in range(0,x):   
        stu.append(input())
        stu.append(input())
        record.append(stu)
        stu = []
    
    namelist = []
     
    sortedrecord = sort(record)
    print(sortedrecord)
    value = 0
    for i,j in sortedrecord:
        if j>sortedrecord[0][1]:
            
            value = j
            break
    
    for i,j in sortedrecord:
        if j==value:
            namelist.append(i)  
    
    namelist.sort()
    
    for i in namelist:
        print(i)       

problem is that the sort fuction is not sorting properly when it has a score of 10

sample input:

4
Shadab
8
Varun
8.9
Sarvesh
9.5
Harsh
10

output:

[['Harsh', '10'], ['Shadab', '8'], ['Varun', '8.9'], ['Sarvesh', '9.5']]
Shadab

note: i have tried alternative sorting ways ,but the condition remains the same.

CodePudding user response:

In the lexicographic order, 10 comes befor 8, because 1 is before 8

You need to convert to float to get it work like you expect

  1. at input

     stu.append(input())
     stu.append(float(input()))
    
  2. or at use

    def sort(sub_li):
        return sorted(sub_li, key=lambda x: float(x[1]))
    
  • Related