简体   繁体   English

lambda函数说明

[英]lambda function explanation

I found the lambda function in internet. 我在互联网上找到了lambda函数。 I am using it and getting the output correctly. 我正在使用它并正确获得输出。 But I need to know the explanation so that i can change the function to my requirements. 但是我需要知道解释,以便我可以根据需要更改功能。

This function is removing any repeated data in the list I have. 此功能正在删除列表中的所有重复数据。 But I am not able to figure out how the L and X values are going on. 但是我无法弄清楚L和X值是如何进行的。 Also what does the l.append(x) or l do here. 另外l.append(x)或l在这里做什么。 Which one will it pick in what condition. 它会在什么条件下选择哪一个。 Please explain. 请解释。 Let us assume that Columns["Hello"] has [1,1,2,3,4,5,6,6,7,8,9,9,10,0] 让我们假设Columns [“ Hello”]具有[1,1,2,3,4,5,6,6,7,8,9,9,10,0]

repeating_data = reduce(lambda l, x: 
                             l.append(x) or l if x not in l else l,
                             columns['Hello'], [])

Thanks Rocky 谢谢洛基

I agree, its making code unreadable through complex lambda function. 我同意,它使代码无法通过复杂的lambda函数读取。

The lambda function is roughly equivalent to below (with comments), lambda函数大致等同于以下内容(带有注释),

def ext_function(columns['Hello']):
    #Empty list to accumulate values
    l = []
    #Iterate through column
    for x in columns['Hello']:        
        #if col_value not in l , append
        if x not in l:
            l.append(x)
    return l

And reduce function is applying lambda function in sequence to input list columns['Hello'] and accumulator []. reduce函数是将lambda函数依次应用于输入列表列['Hello']和累加器[]。

Honestly, if you are just looking to get rid of duplicates, you can achieve same with just one line. 老实说,如果您只是想消除重复,只需一行就可以实现相同的效果。

l = list(set(Columns["Hello"]))

Hope this helps. 希望这可以帮助。

I would use set to find unique items in a list. 我将使用set在列表中查找唯一项。

unique_items = list(set(columns["Hello"]))

To explain what is happening in that piece of code, the trick is in reduce and not so much in lambda . 为了解释这段代码中发生的事情,诀窍在于reduce而不是lambda At a high level, lambda there is doing the uniqueness check and reduce is passing the items from your list to the lambda function. 在较高的层次上,lambda会进行唯一性检查,而reduce会将列表中的项目传递给lambda函数。

To explain lambda part of that code, lambda creates a function object which in that case is taking 2 inputs, l and x and passing them to the expression, (l.append(x) or l) if x not in l else l added the braces around l.append(x) or l, to make it easier to read, as the rest is just an if else statement. 为了解释该代码的lambda部分,lambda创建了一个函数对象,在这种情况下,它接受2个输入lx并将它们传递给表达式(l.append(x) or l) if x not in l else l添加(l.append(x) or l) if x not in l else l围绕l.append(x)或l的花括号,以便于阅读,因为其余的只是if else语句。

To really understand how it is working, as mentioned earlier, the trick is in reduce and the linked python documentation does a very good job of explaining that. 如前所述,要真正了解它是如何工作的,诀窍在于reduce,而链接的python文档在解释这一点方面做得非常好。

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

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