Как сравнить элемент с другим элементом, находящимся внутри вложенного списка? (в python) - PullRequest
0 голосов
/ 01 августа 2020

Мне дают список, который содержит имена и оценки некоторых студентов в форме другого списка.

Например: lis = [['barry', 35], ['larry ', 20], [' cathy ', 10], [' mathew ', 10]]

Мне нужно найти имя / имена ученика со вторым наименьшим баллом. для приведенного выше ввода ответы будут такими: cathey Mathew

Я попытался решить эту проблему следующим образом. Но выхода нет. Может ли кто-нибудь определить ошибку в моем коде?

x=int(input()) #total number of element
lis=[]         #list
pis=[]
for _ in range(x) :

    name = input()    
    score = float(input())
    lis.append([name,score]) #appending name and score to lis
    pis.append([score])       #appending only scores to pis
pis.sort()    #sorting pis
lis.sort()    #sorting lis

x=pis[1]      #finding the 2nd smallest score in pis

for i in lis:

    
    if ((i[1])) == x:  #comparing the second smallest number to every score in lis

        print (i[0])    #printing only  the name if the scores are same,(this step don't work)

1 Ответ

0 голосов
/ 02 августа 2020
x=int(input()) 
lis = [] 
for _ in range(x):
    name = input()    
    score = float(input())
    lis.append([name,score])

#changing list into a dict for sorting the data by its value. 
lis = dict(lis)

#using lambda function inside sorted() for targeting the value in dictionary to be sorted.
sort_orders = sorted(lis.items(), key=lambda x: x[1])

#used for loop here to only print first two key items of the dictionary sort_orders.
for i in range(2):
    print(sort_orders[i][0], end = " ")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...