I am trying to use print inside lambda. Something like that:
lambda x: print x
I understand, that in
I guess there is another scenario people may be interested in: "print out the intermediate step value of the lambda function variables"
For instance, say I want to find out the charset of a collection of char list:
In [5]: instances = [["C","O","c","1","c","c","c","c","c","1","O","C","C","N","C"],
...: ["C","C","O","C","(","=","O",")","C","C","(","=","O",")","c"],
...: ["C","N","1","C","C","N","(","C","c","2","c","c","c","(","N"],
...: ["C","l","c","1","c","c","c","2","c","(","N","C","C","C","["],
...: ["C","C","c","1","c","c","c","(","N","C","(","=","S",")","N"]]
one way of doing this is to use reduce:
def build_charset(instances):
return list(functools.reduce((lambda x, y: set(y) | x), instances, set()))
In this function, reduce
takes a lambda
function with two variables x, y
, which at the beginning I thought it would be like x -> instance
, and y -> set()
. But its results give a different story, so I want to print their value on the fly. lambda
function, however, only take a single expression, while the print would introduce another one.
Inspired by set(y) | x
, I tried this one and it worked:
lambda x, y: print(x, y) or set(y) | x
Note that print()
is of NoneType, so you cannot do and
, xor
these kinds of operation that would change the original value. But or
works just fine in my case.
Hope this would be helpful to those who also want to see what's going on during the procedure.