From Python filter to lambda

Asked 2 years ago, Updated 2 years ago, 14 views

//dict_heights = {'rohoon_height' : 178, 'yongdam_height': 180, 'sungwoong_height' : 175, 'youngmin_height' : 176, 'Gwangsoo_height': 180}

def height_high(height):
  return 'You're really tall' if height >= 180 else 'will continue to grow. : )'

list(filter(height_high,dict_heights))

Here, filter (function name, agreement) like this

I wrote it because they told me to Error appears

The filter should receive the boolean valueGo

They want me to write the last line like this

//list(filter(lambda name : True if dict_heights[name] >= 180 else False, dict_heights))

I don't understand it theoretically. Please explain

If you want to specify a function with height_high, how do you write in def?

python

2022-09-20 11:00

1 Answers

First, I think you misunderstood the purpose of the filter function. Filter is used to obtain a new set of filtered values from a set such as a list or object.

Error caused by a mismatch in the return data type of the function. The return datatype of the function entered as the first factor must be Boolean. The code returns a String.

When using the filter function, it should be in the following form:

# ...
def height_high(height):
    return True if dict_heights[name] >= 180 else False

# NewHeights will only have elements greater than 180 left.
newHeights = list(filter(height_high,dict_heights))

Looking at your code, you print this message when you are taller than 180 and that message when you are lower than 180... I think you're writing a program like that. In that case, I don't think the filter function will be very helpful.

In that case, the output through repetitive and conditional statements seems to be easier.

I hope it was helpful.


2022-09-20 11:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.