简体   繁体   中英

lambda function explanation

I found the lambda function in internet. 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. Also what does the l.append(x) or l do here. 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]

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.

The lambda function is roughly equivalent to below (with comments),

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 [].

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.

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 . At a high level, lambda there is doing the uniqueness check and reduce is passing the items from your list to the lambda function.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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