如何仅打印亚军姓名?解决TypeError: 'list' object is not callable错误
问题分析与解决
你的代码存在两个核心问题:
- 存储逻辑错误:把姓名和分数拼成字符串存入列表后,
max(s)比较的是字符串的字典序,不是分数的大小。比如"张三, 95"和"李四, 90",字符串比较时"李四..."会比"张三..."大,因为"李"的ASCII码比"张"高,这和分数高低完全无关,根本没法正确找到最高分。 - 语法调用错误:
s(f'{name}')是把列表s当函数调用,列表不是可调用对象,直接触发TypeError。
正确实现代码
要打印亚军(第二高分数)的姓名,得把分数和姓名分开存储,用元组就能让Python正确按分数排序:
if __name__ == '__main__': students = [] for _ in range(int(input())): name = input().strip() score = float(input()) students.append((score, name)) # 以(分数, 姓名)元组存储 # 提取所有分数去重后排序,取倒数第二个就是第二高分数 unique_scores = sorted({score for score, _ in students}) second_highest_score = unique_scores[-2] # 找到对应分数的姓名并打印 for score, name in students: if score == second_highest_score: print(name)
如果你的需求是去掉所有最高分学生后,取剩下的最高分作为亚军(比如存在多个同分最高分的情况),可以用这个版本:
if __name__ == '__main__': students = [] for _ in range(int(input())): name = input().strip() score = float(input()) students.append((score, name)) highest_score = max(score for score, _ in students) # 筛选出非最高分的学生,再找其中的最高分 second_highest = max((s, n) for s, n in students if s != highest_score) print(second_highest[1])
关键说明
- 用元组
(score, name)存储时,Python会优先比较第一个元素(分数),能准确按分数排序。 - 直接打印姓名变量就不会出现单引号,因为姓名本身就是字符串类型,打印时默认输出不带引号。
内容的提问来源于stack exchange,提问作者venzo
相关产品推荐
相关产品推荐

