Can you use list comprehension functions in your methods?

Consider the following code:

a = [... for i in input] i = a.index(f(a)) 

I am wondering if I can do a single line. The obvious attempt:

 i = [... for i in input].index(f([... for i in input])) 

But this solution requires the list to be generated twice. Not so obvious attempt:

 i = [ a.index(f(a)) for a in [[... for i in input],] ] 

Which does the trick, but makes the code really weird.

This leads me to the idea that there is probably the possibility of somehow using the list created with the list in its method call. Something like (both do not work, obviously):

 i = [... for i in input].index(f(_)) # or i = [... for i in input].index(f(self)) 

Can this be done?

+5
source share
2 answers

One way to avoid repeating the list comprehension is to create an anonymous function and call it directly (untested):

 i = (lambda a: a.index(f(a)))([... for i in input]) 

This is still a little ugly. Your first example, which used the temporary variable a , is much clearer. Writing single-line images as an exercise is fun, but it's usually not the best way to write supported code.

+2
source

As you do the recursion task, based on your function, you can mix your function with a list or generator expression.

For example, consider the following code:

 >>> f=lambda x:next(i for i in x if i.startswith('a')) >>> >>> a=['df','sr','t','aaf','ar','trf'] >>> a.index(f(a)) 3 

You can navigate as follows using enumerate :

 >>> next(i for i,j in enumerate(a) if j.startswith('a')) 3 

So, all of this is based on your function , that you can put your structure into an understanding of a list or expression of a generator, and then apply some changes to it and use python tools based on your needs (in this case we used enumerate ).

+6
source

All Articles