TypeError: 'float' object is not iterable.
在我的代码中,我使用了嵌套列表推导,得分是浮点值。
问题:给定N名学生的物理课中每个学生的姓名和成绩,将它们存储在嵌套列表中,并打印出第二名学生的姓名最低成绩。
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
l=[[x,y] for x in name for y in score if (max(score)-y) > 0]
max=l[0]
for mark in l:
if mark[1]>max[1]:
max=mark
m=[x[0] for x in l if (max-x[1])==0]
print(m.sort())
答案 0 :(得分:1)
因此,正如我在评论中所说,但更为详细。您需要将学生信息保留在列表中,然后对成绩进行排序以找到第二低的成绩,然后再次遍历它们以打印第二低的成绩。
我也高度建议不要使用max
作为变量名称,因为它会代替内置变量。
students = []
for i in range(1, int(input("How many students? "))+1):
name = input(f"What is student {i}'s name? ")
score = float(input(f"What is student {i}'s grade? "))
students.append([name, score])
second_lowest_grade = sorted({s[1] for s in students})[1]
for student in students:
if student[1] == second_lowest_grade:
print(*student, sep=': ')
答案 1 :(得分:0)
我增强了第一条评论:
#!/usr/bin/env python
students = []
for i in range(1, int(input("How many students? "))+1):
name = input(f"What is student {i}'s name? ")
score = float(input(f"What is student {i}'s grade? "))
students.append([name, score])
student_with_second_lowest_grade = sorted(students, key=lambda t:t[1])[1]
print("Student {0} has the second lowest grade={1}!".format(*student_with_second_lowest_grade))
因此您可以通过以下方式执行:
# python3 test.py
How many students? 4
What is student 1's name? John
What is student 1's grade? 10
What is student 2's name? Mary
What is student 2's grade? 9
What is student 3's name? Ken
What is student 3's grade? 8
What is student 4's name? Peter
What is student 4's grade? 7
Student Ken has the second lowest grade=8.0!
仅供参考