Python 对嵌套列表进行排序以获得第二个最低分数
给出一个学生物理课上每个学生的姓名和成绩,将其存储在嵌套列表中,并打印成绩第二低的任何学生的姓名。注意:如果有多个学生成绩相同,请按字母顺序排列他们的名字,并在新行上打印每个名字 输入:Python 对嵌套列表进行排序以获得第二个最低分数,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,给出一个学生物理课上每个学生的姓名和成绩,将其存储在嵌套列表中,并打印成绩第二低的任何学生的姓名。注意:如果有多个学生成绩相同,请按字母顺序排列他们的名字,并在新行上打印每个名字 输入: 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(inp
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]]
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]]
[['Akriti', 41],
['Harsh', 39],
['Harry', 37.21],
['Berry', 37.21],
['Tina', 37.2]]
[41, 39, 37.21, 37.21, 37.2]
要回答您的问题,您可以将嵌套列表的输入作为
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])
以下是我针对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])
一个老问题,但添加了一个答案,以便获得帮助
这确实是一个来自中国的采访问题
下面是我对这个问题的简单解决方案——我只需迭代嵌套的等级列表。在每次迭代中,新的分数将与最低的
分数和第二低的分数(最慢的
)进行比较,同时维护一个分数等于第二低分数的名称列表
注意:名称
始终与最慢的
分数相关联,如果最慢的
更改,我们也会更改名称
。如果新分数等于最慢的
分数–添加新名称。评论将帮助你进一步
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)))
def第二级(等级):
"""
返回得分第二低的学生的姓名列表
"""
#初始化“最低”和第二低的“最慢”分数和名称
等级=国际热核实验堆(等级)
lname,最低=下一个(等级)
slname,最慢=下一个(年级)
如果最慢<最低:
最低,最慢=最慢,最低
名称=[lname]
elif slowest==lowest:#我们不知道,如果lowest可以是第二个lowest!
名称=[lname,slname]
其他:
名称=[slname]
姓名、成绩:
如果得分==最慢:
name.append(name)
持续
如果得分==最低:
持续
如果得分<最低:
如果最慢==最低:
通过
其他:
名称=[lname]
最低,最慢=分数,最低
lname=名称
elif分数<最慢:
最慢=得分
名称=[名称]
elif得分>最慢和最慢==最低:
最慢=得分
名称=[名称]
如果最慢==最低:#所有人得分相同
返回[]
names.sort()
返回名称
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
嵌套的_列表=[]
对于范围内的(int(原始输入()):
名称=原始输入()
分数=浮动(原始输入()
嵌套的列表。追加([名称,分数])
断言2这是我的解决方案。
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])
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])
您可以使用:
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)
如果uuuu name_uuuu=='\uuuuuuu main\uuuuuu':
python_学生=[]
新列表=[]
对于范围内的(int(input()):
名称=输入()
分数=浮动(输入()
数据=[姓名、分数]
python_students.append(数据)
python_students.sort(key=lambda x:x[1])
minvalue=python_学生[0][1]
第二个值=0
对于我在python_的学生:
如果(最小值
如果uuuuu name uuuuuu=='\uuuuuuu main\uuuuuuu':
n=[]
s=[]
对于范围内的(int(input()):
名称=输入()
n、 附加(名称)
分数=浮动(输入()
s、 附加(分数)
a=最大值(s)
b=最小值(s)
对于范围内的i(len(n)):
如果s[i]b:
a=s[i]
对于范围内的j(len(n)):
如果s[j]==a:
打印(n[j])
使用两个指针表示最低(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)))
def获得第二名最低年级学生(学生记录):
f、 s=浮点('inf'),浮点('inf'))
fl_名称,sl_名称=[],[]
对于学生记录项()中的(分数、姓名):
如果分数
这里可能是解决这个问题最有效的方法
“”
此解决方案非常高效,因为它使用
heapsort和二进制搜索。它只排序一次
然后使用二进制搜索快速查找
具有相同属性的所有值的边界
等级而且,由于它已排序,因此它会从
循环一次,它收集列组的所有值。
'''
从对分导入对分,左对分
从heapq导入heappush、heappop
n=2
学生_分数=[]
分数_排序=[]
学生成绩排序=[]
序数_映射={}
seen=set()
枚举=1
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
对于范围内的(int(input()):
名称=输入()
分数=浮动(输入()
heappush(学生分数,(分数,姓名))
对于范围内的i(len(学生分数)):
val_to_append=heappop(学生分数)
已排序的分数。追加(val\u to\u追加[0])
学生分数已排序。附加(val到附加)
如果val_to_append[0]未出现:
如果枚举>n:
打破
seen.add(val_to_append[0])
序号映射[enum]=val\u to\u追加[0]
枚举+=1
低=左二等分(分数已排序,顺序映射[n])
高=对分(分数排序,顺序映射[n])
对于范围内的i(低、高):
打印(学生成绩排序[i][1])
我不知道这是否是一种很好的编码方式,但它可以工作。使用基本的Python功能
- 列表压缩
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)
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]).
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)
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__':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)
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)
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]))
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])
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)
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)
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")
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 -->
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()))]
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))])])
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
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)
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)
n = int(input())
mainlist = []
marks_list = []
for _ in range(n):
name = input()
marks = float(input())
marks_list.append(marks)
list1 = []
list1.append(name)
list1.append(marks)
mainlist.append(list1)
marks_list_set = sorted(marks_list)
nameslist = []
length = len(mainlist)
i = 0
while i < length:
if(mainlist[i][1] == marks_list_set[1]):
nameslist.append(mainlist[i][0])
i += 1
nameslist=sorted(nameslist)
for _ in nameslist:
print (_)
students_scores = []
for _ in range(int(input())):
name = input()
score = float(input())
students_scores.append([name, score]) # create input array
unique_scores_set = set((x[1] for x in students_scores)) # calculate unique scores
second_lowest_score = sorted(unique_scores_set)[1] # calculate second lowest score
output = [y[0] for y in students_scores if y[1] == second_lowest_score] # create output array containing names of students with the second lowest score
output.sort() # sort the names aplphabetically in place
print (*output, sep="\n") #print output list one line at a time