Home>

I'm trying to get the maximum even number from the Python list with the code below, but I get an error.
I understand that the code below else is bad, but I don't know how to write it.
I would appreciate it if you could teach me.

print (max ([1,5,81,41, -54,2], key = lambda x: x if x% 2 == 0 else continue))
  • Answer # 1

    If there are no even numbers (the list is empty)defaultYou can specify.

    lst = [1, 2, 3, 4, 5]
    print (max ([n for n in lst if n% 2 == 0], default = 0))
    # Four
    lst = [1, 3, 5]
    print (max ([n for n in lst if n% 2 == 0], default = 0))
    # 0

    ↑ Returns 0 if there is no even number

  • Answer # 2

    If you want to take advantage of the original shape, use "negative infinity"

    import math
    print (max ([1,5,81,41, -54,2], key = lambda x: x if x% 2 == 0 else -math.inf))


    Practically-math.infNot-9999I think it's okay.

    If you use it for general purposes, you also need to decide what you want to do when there are no even numbers.

  • Answer # 3

    If you want to write in one line, is it here?
    [x for x in [1,5,81,41, -54,2] if x% 2 == 0]A list of even numbers is generated in the part of, and its max is taken.

    print (max ([x for x in [1,5,81,41, -54,2] if x% 2 == 0]))

  • Answer # 4

    print (([None] + sorted (filter (lambda x: x% 2 == 0, a))) [-1])

    Execution example