Is there a better way to make this Python code?

Looking at this piece of python code, I wrote:

return map(lambda x: x[1], filter(lambda x: x[0] == 0b0000, my_func(i) ) ) 

(Hoping this will be clear)

I am wondering if python has a better way to do this?

I learned python a few months ago, wrote some scripts and have not used it since. This puts me in a strange place to learn, because I know enough to do what I want, but I donโ€™t have the novice instinct to find the โ€œrightโ€ way. I hope this question brings me back on track ...

+6
python
source share
4 answers

I think you want to understand the list:

 [x[1] for x in my_func(i) if x[0] == 0] 

List Explanations - An extremely common Python idiom.

+9
source share

You can use something like:

 return [x[1] for x in my_func(i) if x[0] == 0b0000] 

Many people would call it โ€œbetterโ€ as their smaller and more obvious.

(I will be tempted to consider turning it into a simple loop and an if statement. Functional programming is good, but simple loops are good too.)

+2
source share

If you write in Python 3.x, you can write an efficient generator expression, for example: return (x[1] for x in my_func(i) if not x[0])

+1
source share

In python 3.x, you can use decompression to avoid using x[0] and x[1] . You might also consider returning the generator expression instead of understanding the list if you want to examine the result only once:

 return (y for x,y,*z in my_func(i) if x == 0b0000) 
+1
source share

All Articles