Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
Lambda with if statement

Let say I have a list called "y_pred", I want to write a lambda function to change the value to 0 if the value is less than 0.

Before: y_pred=[1,2,3,-1]

After: y_pred=[1,2,3,0]

I wrote something like this, and return an error message

y_pred=list(lambda x: 0 if y_pred[x]<0 else y_pred[x])    
TypeError: 'function' object is not iterable
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You want an expression (a if cond else b) mapped over your list:

y_pred_before = [1, 2, 3, -1]
y_pred_after = list(map(lambda x: 0 if x < 0 else x, y_pred_before))
# => [1, 2, 3, 0]

A shorter form of the same thing is a list comprehension ([expr for item in iterable]):

y_pred_after = [0 if x < 0 else x for x in y_pred_before]

Your error "TypeError: 'function' object is not iterable" comes from the fact that list() tries to iterate over its argument. You've given it a lambda, i.e. a function. And functions are not iterable.

You meant to iterate over the results of the function. That's what map() does.

over 4 years ago · Santiago Trujillo Denunciar

0

You can use numpy (assuming that using lambda is not a requirement):

import numpy as np
y_pred = np.array(y_pred)
y_pred[y_pred < 0] = 0
y_pred

Output:

array([1, 2, 3, 0])
over 4 years ago · Santiago Trujillo Denunciar

0

An easy way to do this with list comprehension:

y_pred=[x if x>0 else 0 for x in y_pred_before] 
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda