传统循环判断代码转列表推导式结果错误,求修正方法
列表推导式实现年龄判断结果不符的问题分析
你用传统循环实现了年龄是否成年的判断,输出[0, 1, 1, 0, 1]是正确的:
edades = [10, 25, 49, 16, 60] mayores_edad = [] for edad in edades: if edad >= 18: mayores_edad.append(1) else: mayores_edad.append(0) print("Mayores de edad:", mayores_edad)
但你写的列表推导式得到了错误结果[10, 0, 0, 16, 0]:
mayores_edad_por_compresion = [x if (x >= 18) == 1 else 0 for x in edades] print(mayores_edad_por_compresion)
错误原因
你的代码存在两个问题:
- 三元表达式返回值错误:满足
x >=18条件时,你返回的是变量x(即年龄数值),而不是需求中的1,这导致符合条件的位置输出年龄本身,而非预期的1。 - 多余的条件比较:
(x >=18) ==1完全没必要,x >=18本身会返回布尔值True或False,Python中True等价于1、False等价于0,不需要额外和1做比较。
正确写法
写法一:标准三元表达式
直接在条件满足时返回1,不满足时返回0:
edades = [10, 25, 49, 16, 60] mayores_edad_por_compresion = [1 if x >= 18 else 0 for x in edades] print(mayores_edad_por_compresion) # 输出: [0, 1, 1, 0, 1]
写法二:利用布尔值转整数
Python中布尔值可以直接转为整数(True→1,False→0),简化代码:
edades = [10, 25, 49, 16, 60] mayores_edad_por_compresion = [int(x >= 18) for x in edades] print(mayores_edad_por_compresion) # 输出: [0, 1, 1, 0, 1]
内容的提问来源于stack exchange,提问作者pab1994
相关产品推荐
相关产品推荐

