user6952870 - 1 year ago 77
Python Question

# how to take a lambda function as an input

the separate function takes a function and list and return two list, my question is how to translate the following function to the lambda input to make my separate function work? (the first input in my separate function is incorrect, it raise a syntax error)

def function(x:list):
for y in x:
if y > x[0]:
return True
else:
return False

separate(lambda x: for y in x: y > x[0], l):

If you can use map:

separate(lambda x: map(lambda y : y > x[0], x))

Which returns a map object

>>>
>>> z = lambda x: map(lambda y : y > x[0], x)
>>> list(z([1,2,3]))
[False, True, True]
>>> list(z([10, 2, 3, 11, 9]))
[False, False, False, True, False]
>>>

The outer lambda takes the list as its input (x) and returns the result of map. The second lambda is mapped over the elements of x - map provides the iteration.

Or just use a list comprehension

separate(lambda x: [y > x[0] for y in x])

>>> z = lambda x: [y > x[0] for y in x]
>>> list(z([10, 2, 3, 11, 9]))
[False, False, False, True, False]
>>>

Unwrap the list comprehension to a regular function definition to compare with function in your post

def function(x:list):
result = []
for y in x:
result.append(y > x[0])
return result
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download