【问题标题】:Sorting nested lists for second lowest score [duplicate]对第二低分数的嵌套列表进行排序[重复]
【发布时间】:2019-02-11 20:31:54
【问题描述】:

给定物理课学生中每个学生的姓名和成绩,将它们存储在嵌套列表中,并打印成绩第二低的任何学生的姓名。注意:如果有多个年级相同的学生,请按字母顺序排列他们的姓名并将每个姓名打印在新行上。

输入:

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

输出:

>>Berry
>>Harry

我做到了

if __name__ == '__main__':
l2=[]
l1=[]
for i in range(int(input())):
    name = input()
    l1.append(name)
    score = float(input())
    l1.append(score)
    l2.append(l1)
print(l2)

但它输出:

>>[['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]

【问题讨论】:

  • 第一部分很简单,您的l2 列表正在收集所有信息以供结束,因此在循环之前进行初始化是好的,但l1 正在为每对输入收集,所以你不应该在收集之前在循环内初始化?也许l1 = [] 在循环内的任何输入之前。
  • [['Harry', 37.21, 'Berry', 37.21, 'Tina', 37.2, 'Akriti', 41.0, 'Harsh', 39.0], ['Harry', 37.21, 'Berry ', 37.21, 'Tina', 37.2, 'Akriti', 41.0, '苛刻', 39.0], ['Harry', 37.21, 'Berry', 37.21, 'Tina', 37.2, 'Akriti', 41.0, '苛刻' ', 39.0], ['Harry', 37.21, 'Berry', 37.21, 'Tina', 37.2, 'Akriti', 41.0, 'Harsh', 39.0], ['Harry', 37.21, 'Berry', 37.21, '蒂娜',37.2,'Akriti',41.0,'苛刻',39.0]]
  • 第一:问题标题中的错别字,第二:寻求家庭作业问题的解决方案... Stackoverflow 的目标不是帮助学生避免家庭作业。

标签: python python-3.x python-2.7


【解决方案1】:

要回答您的问题,您可以将嵌套列表的输入作为

n=int(input())
arr=[[input(),float(input())] for _ in range(0,n)]

我相信这是一个黑客等级问题 这是解决它的方法

n=int(input())
arr=[[input(),float(input())] for _ in range(0,n)]
arr.sort(key=lambda x: (x[1],x[0]))
names = [i[0] for i in arr]
marks = [i[1] for i in arr]
min_val=min(marks)
while marks[0]==min_val:
    marks.remove(marks[0])
    names.remove(names[0])    
for x in range(0,len(marks)):
    if marks[x]==min(marks):
        print(names[x])

【讨论】:

  • 它应该打印第二低标记。不是最低的。
  • @ashgetstazered 再次阅读代码,我首先将标记排序为升序,并将我的键作为列表的整数元素,然后我删除所有最高实例,即第一个元素,因此给了我第二高的
  • 这里需要使用lambda函数吗?
  • Lambda 在这里是因为我们需要多个排序标准,第一个是 x[1],它只是学生的分数,第二个标准是如果分数相似,他们应该按字母顺序排列因此 x[0]
【解决方案2】:

使用基本 Python 功能

  • 列表理解(带条件)
  • 使用列表排序(就地)
  • 使用集合获取唯一值(技巧 17c)

您可以在 Linux 或 Windows shell 的命令行中将以下内容作为脚本运行。

它希望您通过首先输入一个整数来输入数据,该整数给出了要遵循的记录数。

该代码适用于上述问题中给出的示例以及其他情况。它检查可能引起麻烦的最重要的数据相关边缘情况。

if __name__ == '__main__':

    # Note, Python evaluates expressions from left to right, which helps us
    # to do the following. After reading the integer used within the range
    # it will read [str, float] combinations as many times as the
    # range requests
    inputs = [[str(input()), float(input())] for dummy in range(int(input()))]

    # Given the inputs, find the unique score values first. Then we take
    # the second lowest from it and search for the names of the students
    # with this score.
    #
    # Additionally, we validate the inputs to check for edge cases where
    # the question cannot be answered at all. This depends on the data
    # given.
    #
    # To get the unique score values we use the trick to convert to a
    # set and back to a list
    #
    unique_scores = list(set([score for name, score in inputs]))

    # Let's deal with the edge cases. For these we return simply None.
    students = None

    if len(unique_scores) == 0:
        # It might be that no data has been provided. We could handle this earlier
        # but let's do it here, with the other cases.
        # Let's return None in this case
        #
        print('No data provided. Cannot answer your question.')
    elif len(unique_scores) == 1:
        # Suppose, you have quiete some students, but all have the same grade.
        # So there is no second lowest. Let's be strict now and return None
        # in this case too.
        #
        print('Found only one distinct score. Cannot answer your question.')
    else:
        # Finally, after all checks passed we return the names of those students,
        # which have the second lowest case.
        unique_scores.sort()
        second_lowest_score = unique_scores[1]
        students = [name for name, score in inputs if score == second_lowest_score]

    # Finally, present the result
    print(students)

【讨论】:

    【解决方案3】:

    这个问题绝对是黑客级别的。以下是简单的解决方案。

     if __name__ == '__main__':
        student = []
        for _ in range(int(input())):
            name = input()
            score = float(input())
            student.append([score,name])
        
        # Sort list in Ascending order
        student.sort()
    
        # Assign the first score to a list which will be the minimum
        grade = student[0][0]
        
        # Loop through the list by excluding first item in the list and find the second lowest
        for i in range(1,len(student)):
            if grade < student[i][0]:
                grade = student[i][0]
                break
        
        # Loop through the list and print names based on the second lowest score
        for i in range(1,len(student)):
            if student[i][0] == grade:
                print(student[i][1])
    

    【讨论】:

    • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
    • 好的代码不需要解释,阅读应该很容易理解。这个答案很容易阅读,是这里最好的答案之一。
    【解决方案4】:
    if __name__ == '__main__':
    
        n = []
        s = []
        for _ in range(int(input())):
            name = input()
            n.append(name)
            score = float(input())
            s.append(score)            
        a=max(s)
        b=min(s)
        for i in range(len(n)):
            if s[i]<a and s[i]>b:
                a=s[i]
    
        for j in range(len(n)):
            if s[j]==a:
                print(n[j])
    

    【讨论】:

    • 这行得通,但最后应该使用排序方法进行排序。
    【解决方案5】:
    if __name__ == '__main__':
        score_list={}
        for _ in range(int(input())):
            name = input()
            score = float(input())
            score_list[name]=score
        second_val=sorted(set(score_list.values()))[1]
        print('\n'.join(sorted ([name for name,val in score_list.items() if val==second_val])))
    

    说明: 我已经使用了字典。我首先获取输入,然后通过制作一个值列表然后对其进行排序以获取值来找出第二个最小值。 然后在打印语句的下一行,我从dict中取出key为name,value为val,用于验证条件满足条件匹配第二个最小值,然后命名为排序(如果不止一个) 并通过 '\n' 加入下一步并打印。

    【讨论】:

      【解决方案6】:

      一个老问题,但添加一个答案以便获得帮助

      这确实是hackerrank的面试题。

      下面是我对这个问题的简单解决方案——我只是遍历嵌套的成绩列表。并且在每次迭代中,都会将新分数与 lowest 分数和第二低分数 (slowest) 进行比较,同时维护一个 names 列表,这些分数等于第二低分数。

      注意:names 始终与slowest 分数相关联,如果slowest 更改,我们也会更改names。如果新分数等于 slowest 分数 - 添加新名称。评论将帮助您进一步...

      def second_lowests(grades):
          """
          returns list of names of students with second lowest score
          """
          # intialize the `lowest` and second lowest `slowest` score and names
          grades = iter(grades)
          lname, lowest = next(grades)
          slname, slowest = next(grades)
          if slowest < lowest:
              lowest, slowest = slowest, lowest
              names = [lname]
          elif slowest == lowest: # we don't know, if lowest can be second lowest!
              names = [lname, slname]
          else:
              names = [slname]
      
          for name, score in grades:
              if score == slowest:
                  names.append(name)
                  continue
              if score == lowest:
                  continue
              if score < lowest:
                  if slowest == lowest:
                      pass
                  else:
                      names = [lname]
                  lowest, slowest = score, lowest
                  lname = name
              elif score < slowest:
                  slowest = score
                  names = [name]
              elif score > slowest and slowest == lowest:
                  slowest = score
                  names = [name]
      
          if slowest == lowest: # all have same score
              return []
          names.sort()
          return names
      
      
      if __name__ == '__main__':
          nested_list = []
          for _ in range(int(raw_input())):
              name = raw_input()
              score = float(raw_input())
              nested_list.append([name, score])
          assert 2 <= len(nested_list) <= 5
          print ("\n".join(second_lowests(nested_list)))
      

      我不知道这是否是一个更好的解决方案,但它通过了所有测试用例。

      【讨论】:

        【解决方案7】:
        if __name__ == '__main__':
            total = []
            for i in range(int(input())):
                name = input()
                score = float(input())
                name_score = list((score, name))
                total.append(name_score)
            total.sort()
            min_mark = total[0][0]
            count = 0
            for i in range(len(total)):
                if min_mark == total[i][0]:
                    count = count+1
            if count >= 1:
                for j in range(count):
                    total.pop(0)
            nd_min_mark = total[0][0]
            for i in range(len(total)):
                if nd_min_mark == total[i][0]:
                    print(total[i][1])
        

        【讨论】:

        • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
        【解决方案8】:
        if __name__ == '__main__':
            python_students = []
            new_list = []
            for _ in range(int(input())):
                name = input()
                score = float(input())
                data = [name, score]
                python_students.append(data)
        
        
        python_students.sort(key = lambda x: x[1])
        minvalue = python_students[0][1]
        secondValue = 0
        for i in python_students:
            if(minvalue < i[1]):
                secondValue = i[1]
                break
        
        for i in python_students:
            if(secondValue == i[1]):
                new_list.append(i[0])
        
        new_list.sort()
        
        for i in new_list:
            print(i)
        

        【讨论】:

        • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
        【解决方案9】:
        if __name__ == '__main__':n=int(input())
        
            names=[]
            scores=[]
            for i in range(n):
                name=input()
                names.append(name)
                score=float(input())
                scores.append(score)
            dic=dict(sorted(zip(names,scores)))
        
            mini=(min(scores))
            cnt=scores.count(mini)
        
            for i in range(cnt):
                scores.remove(mini)
            minim=min(scores)
            for i,j in dic.items():
                if j==minim:
                    print(i)
        

        【讨论】:

        • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
        【解决方案10】:

        这是上述问题的解决方案

        temp_list = []
        
        n=int(raw_input())
        if 2<=n<=5:
            for _ in range(n):
                name = raw_input()
                score = float(raw_input())
                temp_list.append((name,score))
            
            required_dict = dict(temp_list)
            scores_list = [x[1] for x in temp_list]
        
            second_last_score = sorted(list(set(scores_list)))[1]
            temp_list = []
            for key,val in required_dict.items():
                if val == second_last_score:
                    temp_list.append(key)
        
            for _ in sorted(temp_list):
                print(_)
        else:
            print("Please provide n >= 2 and n<=5")
            
        

        【讨论】:

        • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
        【解决方案11】:

        这是我为解决问题所做的诚实努力。

        # Run it in Python 3
        
        students = int(input()) # taking the inputs
        parentlist = [] # for saving both the students and the marks in an array
        scores = list() # seperate list for the scores
        newlist = [] 
        sec_low = []
        
        # saving elements in the array
        for i in range(0, students):
            name = input()
            score = float(input())
            parentlist.append([name, score])
            scores.append(score)
        
        scores.sort() # sorting score in ascending order
        res = []
        [res.append(x) for x in scores if x not in res] # with the help of res checking for repetation of marks in the scores list
        
        # taking the marks in the 1st position and comparing with the 2nd lowest in the parentlist.
        for i in parentlist:
            if (res[1] == i[1]):
                newlist.append(i[0]) # appending the names of students having 2nd lowest marks to newlist
        
        # sorting the newlist alphabetically and printing values
        newlist.sort()
        for i in newlist:
            print(i)
        

        【讨论】:

        • 请对您的代码进行一些解释
        • @mishsx 我想现在看起来很有说服力?
        【解决方案12】:

        这是我对这个 Hackerrank 练习的解决方案:

        if __name__ == '__main__':
                students = []
                for _ in range(int(input())):
                    name = input()
                    score = float(input())
                    new = [name, score]
                    students.append(new)
        
        
        def removeMinimum(oldlist):
         oldlist = sorted(oldlist, key=lambda x: x[1])
         min_ = min(students, key=lambda x: x[1])
         newlist = []
        
         for a in range(0, len(oldlist)):
             if min_[1] != oldlist[a][1]:
                newlist.append(oldlist[a])
        
         return newlist
        
        students = removeMinimum(students);
        # find the second minimum value 
        min_ = min(students, key=lambda x: x[1])
        # sort alphabetic order 
        students = sorted(students, key=lambda x: x[0])
        for a in range(0, len(students)):
             if min_[1] == students[a][1]:
              print(students[a][0])
        

        【讨论】:

        • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
        【解决方案13】:

        这是我的解决方案。

        students = [[input(), float(input())] for _ in range(int(input()))]
        students.sort(key=lambda x: (x[1], x[0]))
        first_min_score = students[0]
        second_min_score = min(students, key=lambda x: (x[1]==first_min_score[1], x[1]))
        for student in students:
            if student[1] == second_min_score[1]:
                print(student[0])
        

        【讨论】:

        • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
        【解决方案14】:

        你可以使用:

        start=int(input())
        for _ in range(start):
            print("enter Name: ")
            name = input()
            print("enter Score: ")
            score = float(input())
            d[name]=score
            l = sorted(d.items(),key=lambda x: x[0])
        m=min(l,key=lambda item:item[1])
        #print("minumul este: ")
        #print(m)
        l.remove(m)
        print("lista este: ")
        for i in l:
            if i[1]==m[1]:
                #print(rf"elementul {i[1]} a fost exclus")
                l.remove(i)
        print(l)
        n=min(l,key=lambda item:item[1])
        #print(n)
        nn=[]
        for i in  l:
            if i[1]==n[1]:
                nn.append(i[0])
        
        for i in sorted(nn):
            print(i)
        

        【讨论】:

        • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
        【解决方案15】:
        # function for removing duplicate elements
        def Remove(scorelist):# scorelist is sorted list with duplicate element
            uniquelist=[]     #uniquelist is list without duplicate element
            for num in scorelist:
                if num not in uniquelist:
                    uniquelist.append(num)
           # print("this is unique list",uniquelist)        
            return uniquelist
        
        if __name__ == '__main__':
            newlist = [] #list contain name and number both
            scorelist=[] #list contain number only
            finallist=[] 
            n =int(input())
            for i in range(0,n):
                name = input()
                score = float(input())
                scorelist.append(score)
                lst=[name,score]
                newlist.append(lst)
        
            scorelist.sort()
            uniquelist=[]
            uniquelist=Remove(scorelist) #sorted and unique list  
        
            seclow=uniquelist[1] 
            for i in range(len(scorelist)):
                if newlist[i][1]==seclow :
                    finallist.append(newlist[i][0])
            finallist.sort()
            print(*finallist, sep="\n") 
        

        【讨论】:

          【解决方案16】:

          对最低 (f) 和次低 (s) 使用两个指针,并逐个遍历记录进行比较。这应该是 O(N) 复杂度。

          def get_second_lowest_grade_students(student_recs):
              f, s = float('inf'), float('inf')
              fl_names, sl_names = [], []
          
              for (score, names) in student_recs.items():
                  if score < f:
                      s = f
                      f = score
                      sl_names = fl_names
                      fl_names = names
                  elif score < s and score != f:
                      s = score
                      sl_names = names
          
              sl_names.sort()
          
              return sl_names
          
          if __name__ == '__main__':
              student_recs = {}
          
              for _ in range(int(input())):
                  name = input()
                  score = float(input())
          
                  if score not in student_recs:
                      student_recs[score] = []
          
                  student_recs[score].append(name)
          
              print("\n".join(get_second_lowest_grade_students(student_recs)))
          

          【讨论】:

            【解决方案17】:
            from operator import itemgetter
            if __name__ == '__main__':
            
                listt = [] #list will contain name and scores, to know the relation between then
                names = [] #list will contain output names
                n = int(input())
                for _ in range(n):
                    name = input()
                    score = float(input())
                    nested_list = [name,score]
                    listt.append( nested_list ) 
            
                listt.sort( key = itemgetter(1) ) 
                minimum = listt[0][1] #contain the minimum score
                i = 0
                for i in range(0,n):
            
                       # if an element its highest than the minimum, its the second lowest
                    if(listt[i][1] > minimum): 
            
                        # the second lowest
                        minimum=listt[i][1] 
                        names.clear() # clear the names list if we before inserted names in else block
                        while(listt[i][1] == minimum): # of all scores equals to the minimum
            
                            names.append( listt[i][0] ) #Save their names 
                            if i!=n-1: # if is not the last score
                                i+=1
                            else:
                                break
                        break # once we obtain all equals scored, break loop
            
                    else:           # its possible that all students have same score
                        if (listt[i][1] == minimum): # if all score are equal to the minimum
                            names.append( listt[i][0] )
            
                names.sort()
                for name in names:
                    print(name)
            

            【讨论】:

            • 您能解释一下您的解决方案吗?
            【解决方案18】:
            n=int(input())
            stud=[]
            grad=[]
            for i in range(n):
                stu=input()
                stud.append(stu)
                grd=float(input())
                grad.append(grd)
            dic=dict(sorted(zip(stud,grad)))
            
            mini=(min(grad))
            cnt=grad.count(mini)
            
            for i in range(cnt):
                grad.remove(mini)
            minf=min(grad)
            for i,j in dic.items():
                if j==minf:
                    print(i)
            

            【讨论】:

            • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
            【解决方案19】:

            这可能是解决这个问题最有效的方法。

            '''
            This solution is highly efficient because it uses
            heapsort and binary search. It sorts only one time
            and then uses binary search to quickly find the 
            boundaries of all of the values that have the same
            rank. Also, since it is sorted, it breaks out of the
            loop once it collects all of the values for the rank.
            '''
            
            from bisect import bisect, bisect_left
            from heapq import heappush, heappop
            
            n = 2
            student_scores = []
            scores_sorted = []
            student_scores_sorted = []
            ordinal_map = {}
            seen = set()
            enum = 1
            
            if __name__ == '__main__':
                for _ in range(int(input())):
                    name = input()
                    score = float(input())
                    heappush(student_scores, (score, name))
            
            for i in range(len(student_scores)):
                val_to_append = heappop(student_scores)
                scores_sorted.append(val_to_append[0])
                student_scores_sorted.append(val_to_append)
            
                if val_to_append[0] not in seen:
                    if enum > n:
                        break
                    seen.add(val_to_append[0])
                    ordinal_map[enum] = val_to_append[0]
                    enum += 1
            
            low = bisect_left(scores_sorted, ordinal_map[n])
            high = bisect(scores_sorted, ordinal_map[n])
            
            for i in range(low, high):
                print(student_scores_sorted[i][1])
            

            【讨论】:

              【解决方案20】:
              Student=[]
              Grade=[]
              scorel=[]
              namel=[]
              for i in range(int(input())):
                  name = input()
                  Student.append(name)
                  score = float(input())
                  Grade.append(score)
                  scorel.append(score)
              scorel.sort()
              for j in range (len(Grade)):
                  if scorel[-2]==scorel[0]:       
                          if scorel[-1]==Grade[j]:
                              namel.append(Student[j])
                  else:
                      if scorel[0]==scorel[1]:
                          if scorel[2]==Grade[j]:
                              namel.append(Student[j])
              
                      if scorel[0]!=scorel[1]:
                          if scorel[1]==Grade[j]:
                              namel.append(Student[j])
              
              namel.sort()
              for k in range (len(namel)):
                  print(namel[k]).
              

              我不知道这是否是一种好的编码方式,但它确实有效。

              【讨论】:

              • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
              【解决方案21】:

              我参加聚会迟到了吗? 这是我的解决方案。不是最有效的(我认为 thomas 的结果最好),尽管它被划分为只做一件事的函数:

              
              def get_second_lowest_value(sco):
                  s = list(set(sco))
                  if len(s) == 1:
                      return s[0]
                  else:
                      s.sort()
                      return s[1]
              
              
              def get_all_indexes_of_an_element(arr, element):
                  answer = []
                  for i, a in enumerate(arr):
                      if a == element:
                          answer.append(i)
                  return answer
              
              
              if __name__ == '__main__':
              
                  names = []
                  scores = []
                  for _ in range(int(input())):
                      names.append(input())
                      scores.append(float(input()))
              
                  indexes_of_second_lowest_score = get_all_indexes_of_an_element(
                      scores, get_second_lowest_value(scores)
                  )
              
                  second_lowest_names = [names[i] for i in indexes_of_second_lowest_score]
              
                  second_lowest_names.sort()
              
                  for p in second_lowest_names:
                      print(p)
              
              

              进一步阐述托马斯的答案,使其更加简洁:

              if __name__ == '__main__':
              
                  names = []
                  scores = []
                  for _ in range(int(input())):
                      names.append(input())
                      scores.append(float(input()))
              
              
                  sorted_scores = sorted(list(set(scores)))
                  s2 = sorted_scores[1] if len(sorted_scores) > 1 else sorted_scores[0]
                  stu = sorted([n for n, s in zip(names, scores) if s == s2])
              
                  print(stu)
              

              【讨论】:

                【解决方案22】:
                if __name__ == '__main__':
                student={}
                for _ in range(int(input())):
                    name = input()
                    score = float(input())
                    #tmp=[name]
                    if score in student:
                        temp=[]
                        temp=student[score]
                        temp.append(name)
                        student[score]=temp
                    else:
                        temp=[]
                        temp.append(name)
                        student[score]=temp
                key=list(student.keys());
                key.sort()
                temp=list(student[key[1]])
                temp.sort()
                for i in (temp):
                    print(i)         
                #print(student)
                #print(key)
                

                这是所有跟进和易于理解的代码

                【讨论】:

                • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
                【解决方案23】:

                请注意,最后我们需要排序以按字母顺序显示。

                name_and_scores = []
                # Store name and scores
                for _ in range(int(input())):
                    name_and_scores.append([input(), float(input())])
                
                # Finding second minimum score
                second_min_score  = sorted(list(set([marks for name, marks in name_and_scores])))[1]
                
                # Printing second minimum names
                print('\n'.join([name for name,marks in sorted(name_and_scores) if marks == second_min_score]))
                

                【讨论】:

                  【解决方案24】:

                  简单有效

                  if __name__ == '__main__':
                      ls1=[]
                      ls2=[]
                      ls4=[]
                      for _ in range(int(input())):
                          name = input()
                          score = float(input())
                          ls1.append([name, score])
                      for i in ls1:
                          ls2.append(i[-1])
                      
                      ls3 = list(set(ls2))
                      for j in ls1:
                          if j[-1]==ls3[-2]:
                              ls4.append(j[0])
                      ls4.sort()       
                      for k in ls4:
                          print(k)         
                  

                  【讨论】:

                  • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
                  【解决方案25】:
                  if __name__ == '__main__':
                  lst=[]
                  for _ in range(int(input())):
                      name = input()
                      score = float(input())
                      data=tuple((name,score))
                      lst.append(data)
                  lst.sort(key = lambda x: (x[1],x[0]))
                  
                  print(lst)
                  

                  【讨论】:

                  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。 Reference
                  【解决方案26】:

                  对于初学者,此代码可能会有所帮助:

                  if __name__ == '__main__':
                      
                      N = int(input())
                      
                      l2 = []
                      
                      if  2 <= N <= 5:
                          for i in range(N):
                              l1 = []
                              name = input()
                              l1.append(name)
                              score = float(input())
                              l1.append(score)
                              
                              l2.append(l1)
                              
                          scores = set()
                          for i in l2:
                              scores.add(i[1])
                          
                          names = []
                          for i in l2:
                              if i[1] == sorted(list(scores))[1]:
                                  names.append(i[0])
                          for i in sorted(names):
                              print(i)  
                  

                  【讨论】:

                  • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
                  【解决方案27】:
                  for _ in range(int(raw_input())):
                      name = raw_input()
                      score = float(raw_input())
                      score.sort(key=lambda x: (x[1],x[0]))
                      name =[i[0] for i in score]
                      marks = [i[1] for i in score]
                      min_value = min(marks)
                      while marks[0] == min_value:
                          marks.remove(marks[0])
                          name.remove([name[0]])
                      for x in range(0,len(marks)):
                          if marks[x]=min(marks):
                              print(names[x])
                      for j in range(0,n):
                              name = input()
                              score = float(input())
                              list1.append([name,score])
                  
                      k=min([list1[i][1] for i in range(0,n)])
                  
                  
                      for i in range(0,len(list1)-1):
                          if(list1[i][1]==k):
                              list1.remove(list1[i])
                  
                      k=min([list1[i][1] for i in range(0,len(list1))])
                      list2=[]
                      for i in range(0,len(list1)):
                          if(list1[i][1]==k):
                              
                              list2.append(list1[i])   
                      list2.sort()
                  
                      for i in range(0,len(list2)):
                          print(list2[i][0])
                  
                  <!-- end snippet -->
                  

                  【讨论】:

                  • 您好,欢迎来到 SO!虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。请阅读tourHow do I write a good answer?
                  【解决方案28】:

                  这是我的解决方案

                  if __name__ == '__main__':
                      students=[[input(),float(input())] for _ in range(0,int(input()))] #read the students names and marks into an array
                      students.sort(key=lambda x: (x[1],x[0]),reverse=True) #sort the elements(priority to marks then, names)
                      marks = [i[1] for i in students] # get marks from sorted array
                  for i in sorted(students[marks.index(marks[marks.index(min(marks))-1]):marks.index(marks[marks.index(min(marks))])]): #get index of lowest grades and second lowest grades then print the elements between these two points. 
                      print(i[0]) #print the names from the list 
                  

                  工作

                  students=[[input(),float(input())] for _ in range(0,int(input()))]
                  

                  上面一行是将所有输入数据获取到一个数组(students)。 首先我们不给学生。这将由int(input()) 行接收。

                  然后 for 循环运行,其余输入按顺序转到[input(),float(input())](名称在前,然后是标记)

                  输入示例:

                  5
                  Harry
                  37.21
                  Berry
                  37.21
                  Tina
                  37.2
                  Akriti
                  41
                  Harsh
                  39
                  

                  数组内部的数据如下:

                  [['Harry', 37.21],
                   ['Berry', 37.21],
                   ['Tina', 37.2],
                   ['Akriti', 41],
                   ['Harsh', 39]]
                  

                  这一行是按标记和名称对数组进行排序(第一优先于标记,第二优先于名称)

                  students.sort(key=lambda x: (x[1],x[0]),reverse=True)
                  

                  数组里面的数据排序后会是这样的:

                  [['Akriti', 41],
                   ['Harsh', 39],
                   ['Harry', 37.21],
                   ['Berry', 37.21],
                   ['Tina', 37.2]]
                  

                  这一行将从学生数组中读取排序标记

                  marks = [i[1] for i in students]
                  

                  在数组里面,数据会是这样的:

                  [41, 39, 37.21, 37.21, 37.2]
                  

                  这些行可能有点混乱,但它的工作很简单。

                  for i in sorted(students[marks.index(marks[marks.index(min(marks))-1]):marks.index(marks[marks.index(min(marks))])]): #get index of lowest grades and second lowest grades then print the elements between these two points. 
                      print(i[0]) #print the names from the list 
                  

                  为了便于理解,摘录一部分

                  (students[marks.index(marks[marks.index(min(marks))-1]):marks.index(marks[marks.index(min(marks))])])
                  

                  上面这行代码是查找第二低标记的索引范围。 如果我们向此代码提供上述示例输入,则索引位置将在 2-3 之间 所以(哈利标记的位置是索引2,而浆果的标记是索引3),下面的代码与上面的代码相同(如果我们给出上面提到的示例输入)

                   students[2:4]
                  

                  这些行的输出形式会是这样的

                  [['Harry', 37.21], ['Berry', 37.21]]
                  

                  我们只需要此列表中的名称,并且还希望按字母顺序对名称进行排序。

                  for i in sorted(2:4):
                      print(i[0])
                  

                  如果我们提供与上面提到的相同的输入,则上面和下面的行将起到相同的作用。

                  for i in sorted(students[marks.index(marks[marks.index(min(marks))-1]):marks.index(marks[marks.index(min(marks))])]):
                      print(i[0])
                  

                  最后的输出是

                  Berry
                  Harry
                  

                  【讨论】:

                    【解决方案29】:
                        if __name__ == '__main__':
                        arrStudents = []
                        for _ in range(int(input())):
                            name = str(input())
                            score = float(input())
                            arrStudents.append([name, score])
                        
                        name = []
                        marks = []
                        sortedMarks = []
                        finalist = []
                        for i in arrStudents:
                            name.append(i[0])
                            marks.append(i[1])
                        sortedMarks = sorted(list(set(marks)))
                        Secondmin_marks = sortedMarks[1]
                        for j in arrStudents:
                            if j[1] == Secondmin_marks:
                                finalist.append(j[0])
                        for k in sorted(finalist):
                            print(k)
                    

                    【讨论】:

                    • 有没有可能你可以解释你的代码,以便 OP 可以从中学习?
                    【解决方案30】:
                    def minl(l):
                        mx=0
                        ans=[]
                        for [i,j] in l:
                            if j>mx:
                                mx=j
                        for [i,j] in l:
                            if mx>j:
                                mx=j
                        for [i,j] in l:
                            if j==mx:
                                ans+=[[i,j]]        
                        return ans    
                        
                    
                    if __name__ == '__main__':
                        l=[]
                        m=[]
                        for _ in range(int(input())):
                            name = input()
                            score = float(input())
                            r=[name,score]
                            l.append(r)
                        for i in minl(l):
                           l.remove(i)
                            
                        for i in minl(l):
                            m+=[i[0]]
                        
                        for i in sorted(m):
                            print(i)
                    

                    【讨论】:

                    • 虽然这个代码块可能会回答这个问题,但最好能稍微解释一下为什么会这样。
                    猜你喜欢
                    • 1970-01-01
                    • 2020-09-08
                    • 2021-04-23
                    • 2019-02-24
                    • 2013-02-06
                    • 2019-01-17
                    • 1970-01-01
                    相关资源
                    最近更新 更多