No Multiline Lambda in Python: Why not?
Look at the following:
map(multilambda x:
y=x+1
return y
, [1,2,3])
Is this a lambda returning (y, [1,2,3])
(thus map only gets one parameter, resulting in an error)? Or does it return y
? Or is it a syntax error, because the comma on the new line is misplaced? How would Python know what you want?
Within the parens, indentation doesn't matter to python, so you can't unambiguously work with multilines.
This is just a simple one, there's probably more examples.
How to write python lambda with multiple lines?
Use def
instead.
def d(x):
if x:
return 1
else:
return 2
All python functions are first order objects (they can be passed as arguments), lambda
is just a convenient way to make short ones. In general, you are better off using a normal function definition if it becomes anything beyond one line of simple code.
Even then, in fact, if you are assigning it to a name, I would always use def
over lambda
. lambda
is really only a good idea when defining short key
functions, for use with sorted()
, for example, as they can be placed inline into the function call.
Note that, in your case, a ternary operator would do the job (lambda x: 1 if x else 2
), but I'm presuming this is a simplified case.
(As a code golf note, this could also be done in less code as lambda x: bool(x)+1
- of course, that's highly unreadable and a bad idea.)
Python multiline lambda
You can define your lambda on multiple lines if you put the expression in parentheses. This creates an implied line continuation, causing newlines to be ignored up to the closing parenthesis.
>>> func = lambda a,b: (
... b - a if a <= b else
... a*b
... )
>>>
>>> func(23, 42)
19
You can also explicitly use the line continuation character "\", but this is not the approach preferred by the Python style guide. (Not that binding lambdas to names are a good idea to begin with, in fairness...)
>>> func = lambda a,b: \
... b - a if a <= b else \
... a*b
>>>
>>> func(23, 42)
19
Of course, you can only have expressions inside your lambda, and not statements. So proper if
blocks and return
s and the like are still impossible.
Additionally, it may not be necessary to use lambdas here at all, because unlike C# (prior to the recent v. 7.0), Python is capable of nesting full functions:
>>> def method(x,y):
... def func(a,b):
... if a <= b:
... return b - a
... return a * b
... return func(x,y)
...
>>> method(23, 42)
19
Lambda not in function doesn't work for more than one word in Python
You could use str.contains
:
items = ("boxer","boxers","sock","socks")
import numpy as np
df["category1"] = np.where(df['product_name'].str.contains('|'.join(items)),
np.nan, # value is True
'Other') # value if False
output:
product_name category1
0 blue shirt Other
1 medium boxers nan
2 red jackets Other
3 blue sock nan
why are my python lambda functions not working?
.append()
is an in place update, and returns None
, so your current generator is creating a list of None
which can't be compared by sorted()
.
That aside, you don't need to keep track of your newly split items with map()
as it's a generator that is being fed into sorted()
.
Try:
>>> my_list = ["a,a", "b,b", "c,c", "a,b"]
>>> sorted(map(lambda i: i.split(","), my_list))
[['a', 'a'], ['a', 'b'], ['b', 'b'], ['c', 'c']]
Or using a generator expression (my preferred method):
>>> my_list = ["a,a", "b,b", "c,c", "a,b"]
>>> sorted(i.split(",") for i in my_list)
[['a', 'a'], ['a', 'b'], ['b', 'b'], ['c', 'c']]
Why doesn't lambda function accept parameter in bond with sorted()
The key
parameter of sorted
is a function which will be applied to the elements in order to compare them to each other.
Therefore, we only pass the function itself without calling it.
I suggest you read the documentation first next time :)
https://docs.python.org/3/library/functions.html#sorted
Does Lambda function not required?
There should be no difference in the speed of both functions ref: lambda is slower than function call in python, why (spoiler alert, it's not)
A lambda is just a function created with a single expression and no name.
normalize trained data with tensorflow
The best way to explain I think is to see a simpler example:
list(map(lambda n: n * 3, [1, 2, 3, 4, 5]))
>> [3, 6, 9, 12, 15]
In this case you're applying to each (because of map
) element n
of the list [1, 2, 3, 4, 5]
the same operation n * 3
.
In your specific case it's a bit more complicated because you have two variables. What happens is that for each (x, y)
pair of your train_data
you are leaving y
as is, and applying the normalization to x
.
Update, more info on what is a lambda.
This site offers great examples and a good definition of lambda used inside a map
function, like in your case:
A lambda expression is a way of creating a little function inline,
without all the syntax of a def. …The code of the lambda is typically a single expression without
variables or if-statements, and does not use "return". Lambda is
perfect where you have a short computation to write inline.
Related Topics
Multiprocessing VS Multithreading VS Asyncio in Python 3
String Comparison Doesn't Seem to Work for Lines Read from a File
How to Rotate a Matplotlib Plot Through 90 Degrees
Understanding Time.Perf_Counter() and Time.Process_Time()
Find Usa Phone Numbers in Python Script
Possibilities for Python Classes Organized Across Files
Why Doesn't 2._Add_(3) Work in Python
Converting Between Datetime and Pandas Timestamp Objects
The Main() Function Appears to Not Work
How to Access a Function Inside a Function
How to Convert a Password into Asterisks While It Is Being Entered
Python: Urllib2 How to Send Cookie with Urlopen Request
Cannot List Ftp Directory Using Ftplib - But Ftp Client Works
Iso to Datetime Object: 'Z' Is a Bad Directive
Python Equivalent to 'Hold On' in Matlab
Matching Any Character Including Newlines in a Python Regex Subexpression, Not Globally