You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报错‘>=’ not supported between str和int实例的原因及解决

问题分析与解决方法

错误原因

你的students列表是扁平结构,里面交替存放了字符串类型的学生名字和整数类型的分数。当filter遍历列表时,会把每个元素(包括名字字符串)代入lambda表达式,尝试和整数60做>=比较——但Python不允许字符串与整数直接进行这类数值比较,这就是触发类型错误的根本原因。你之前尝试的str()或int()转换没用,是因为没针对正确的元素处理,而且列表的扁平结构本身就不适合直接做统一类型转换。

解决步骤

首先要重构列表结构,把每个学生的名字和分数配对(用元组或字典都可以),再针对分数做判断:

方法1:用元组存储学生信息

# 重构列表,每个元素是(名字,分数)的元组
students = [('Ally',100),
            ('Emo',88),
            ('Stefan',70),
            ('George',60),
            ('Alex',45),
            ('Vasil',32),
            ('Daniel',0)]

# filter时取元组的第二个元素(分数)做判断
passed_students = list(filter(lambda x: x[1] >= 60, students))
print(passed_students)
# 输出:[('Ally', 100), ('Emo', 88), ('Stefan', 70), ('George', 60)]

如果只需要及格学生的名字,可以改成列表推导式:

passed_names = [name for name, score in students if score >= 60]
print(passed_names)
# 输出:['Ally', 'Emo', 'Stefan', 'George']

方法2:用字典存储学生信息

students = [{'name': 'Ally', 'score': 100},
            {'name': 'Emo', 'score': 88},
            {'name': 'Stefan', 'score': 70},
            {'name': 'George', 'score': 60},
            {'name': 'Alex', 'score': 45},
            {'name': 'Vasil', 'score': 32},
            {'name': 'Daniel', 'score': 0}]

passed_students = list(filter(lambda x: x['score'] >= 60, students))
print(passed_students)

内容的提问来源于stack exchange,提问作者daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:50:25