简体   繁体   English

如何在python中创建接受lambda表达式的函数?

[英]How to create function that accepts lambda expression in python?

How do I create a function which accepts lambda expression like,如何创建一个接受 lambda 表达式的函数,例如,

# dummy data
data = [{"dim":["abc","sdc"], "mea":[23,23,134]},{"dim":["jgdf","dfc"], "mea":[34,245,2345]}....]

"""
also note that data may be change, [{"x":[{"dim":["abc","sdc"], "mea":[23,23,134]},{"dim":["jgdf","dfc"], "mea":[34,245,2345]}....], "y":.....},...]

but data structure (dictionary) for keys "dim" & "mea" will remain same.
"""  

def function(data,key=lambda x: x):
    """
    Logic:

    sum1 = sum(i["mea"][0] for i in data)

    return [[data[i]["dim"],data[i]["mea"][0]] for i in range(len(data)) if data[i]["mea"][0] * len(data) / sum1 > 1]

    now i want equivalent lambda function that works for any data 
    constraint is that structure before "dim" & "mea" will change.
    """

how do i create that type of function?我如何创建这种类型的功能?

Any help that is appreciated.任何帮助表示赞赏。

A lambda can be treated like any regular variable that is callable:可以将 lambda 视为可调用的任何常规变量:

def function(data, f):
   return f(data)

In your case to create a max function:在您的情况下,要创建一个 max 函数:

def max(data, key = lambda x: x):
  m = lambda a,b: a if key(a) > key(b) else b
  return reduce(m, data)

or more verbose:或更详细:

def max(data, key = lambda x: x):
  max_ = data[0]
  for d in data:
    if key(d) > key(max_): max_ = d
  return max_

How to optimize this to avoid calling key too often is left as an exercise for the reader.如何优化它以避免过于频繁地调用key留给读者作为练习。

More Examples更多例子

Max:最大限度:

>>> reduce(lambda a,b: a if a['hi'] > b['hi'] else b, [{"hi":0},{"hi":-1},{"hi":9}])
{'hi': 9}

Sum:和:

>>> reduce(lambda a,b: {"hi":a["hi"]+b["hi"]}, [{"hi":1},{"hi":2},{"hi":3}])
{'hi': 6}

More generic:更通用:

>>> def generic(data, f, key = lambda x: x, cons = lambda x: x):
...    return reduce(lambda a,b: cons(f(key(a),key(b))), data)
... 
>>> generic([{"hi":1},{"hi":2},{"hi":3}], lambda a,b: a*b, key = lambda x: x["hi"], cons = lambda x: {"hi":x})
{'hi': 6}

>>> def generic_select(data, f, key = lambda x: x):
...   return reduce(lambda a,b: a if f(key(a), key(b)) else b, data)
... 
>>> generic_select([{"hi":1,"a":"b"},{"hi":0,"a":"c"}], lambda a,b: True if a < b else False, key = lambda x: x["hi"])
{'a': 'c', 'hi': 0}

It depends on what you actually want to do.这取决于你真正想要做什么。 If you want a reduction that applies a bin op use generic if you want a reduction that decides between taking a,b use generic_select .如果您想要应用 bin op 的缩减,请使用generic如果想要在 a,b 之间做出决定的缩减,请使用generic_select

Reduce降低

Reduce isn't available in python3 without an import but you can import it from the functools package.在没有导入的情况下,Reduce 在 python3 中不可用,但您可以从 functools 包中导入它。 It's a very common and simple pattern:这是一个非常常见和简单的模式:

>>> def reduce_(data, f):
...   r = data[0]
...   for r_ in data[1:]:
...     r = f(r, r_)
...   return r
... 
>>> reduce_([1,2,3], lambda a,b: a+b)
6
>>> reduce_([1,2,3], lambda a,b: a if a > b else b)
3

Sometimes it may be necessary to specify an initial value instead of using data[0] :有时可能需要指定初始值而不是使用data[0]

>>> def reduce1(data, init, f):
...   r = init
...   for r_ in data:
...     r = f(r, r_)
...   return r
... 
>>> reduce1([1,2,3], [], lambda a,b: [b]+a)
[3, 2, 1]

A reduction of lambda a,b: [b]+a reverses a list. lambda a,b: [b]+a减少lambda a,b: [b]+a反转列表。 reduce means to reduce a list of values to a single value. reduce意味着将值列表减少到单个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM