Lambda function and 0

I want to create a function that modifies each item in a list using a lambda function.

a = [1,5,2,4] def func1(list,func2): for x in range(len(list)): list[x] = func2(list[x]) func1(a,lambda x: x>3 and 10 or x) print a 

Result: [1,10,2,10]

This is normal. But I change '10' to '0'

 func1(a,lambda x: x>3 and 0 or x) 

The result is [1,5,2,4]

Why is the result not equal to [1,0,2,0]? A.

I'm sorry that I am poor in English.

+4
source share
5 answers

The problem is that 0 evaluates to False , which means using the and - or trick because the conditional expression fails.

Python 2.5 introduces "correct" conditional expressions of the form:

 x = true_value if condition else false_value 

So you can replace:

 lambda x: x>3 and 0 or x 

with:

 lambda x: 0 if x > 3 else x 

Alternatively, you can use the map function to replace func1 if you are not worried about updating the list:

 a = map(lambda x: 0 if x > 3 else x,a) print a 

If you want to change the list in place, you can use the enumerate function to simplify the code a bit:

 def func1(list,func2): for i,x in enumerate(list): list[i] = func2(x) 
+4
source

bool (0) β†’ False

bool (10) β†’ True

+2
source
 a and b or c 

is equivalent (almost since your case proves that it is not) so that

 b if a else c 

So:

 a = [1,5,2,4] def func1(li,func2): for x,el in enumerate(li): li[x] = func2(el) func1(a,lambda x: 0 if x>3 else x) print a 

Note:

  • name list for user object is not good

  • using iteration ()

By the way, have you noticed that you are changing the value of an object external to the function in the function?
 u = 102 def f(x): x = 90 print "u==",u 

result

 u== 102 

In your code, a changes because it is a mutable object

In general, a function has a return. You do not, because you are changing a mutable object.

+1
source

x>3 and 0 or x always returns x , because 0 is False .

Replace it:

 (x > 3 and [0] or [x])[0] 

To obtain:

 func1(a,lambda x: (x>3 and [0] or [x])[0]) 

Result:

 [1, 0, 2, 0] 

How it works:

  • The actual return value is placed in a single list of items.
    Any non-empty list is True , so and or works.
  • Then use [0] to return the value.
0
source

You can rotate it:

 func1(a,lambda x: x<=3 and x or 0) 

(unverified)

0
source

Source: https://habr.com/ru/post/1341273/


All Articles