Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one use list comprehension derivatives in its methods?

Consider the following code:

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

I'm wondering whether I could be able to do an one-liner. Obvious try is:

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

But this solution requires list to be generated twice. Not-so-obvious try is:

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

Which does the trick, but makes code really weird.

This leads me to idea that probably there is possibility to somehow use list, generated by list comprehension, in its own method call. Something like (both not working, obviously):

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

Can it be done?

like image 328
Dmitrii Borisevich Avatar asked May 08 '15 14:05

Dmitrii Borisevich


1 Answers

As you are doing a recursion task, based on what your function does you can mix your function with a list comprehension or a 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 mix like following using enumerate :

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

So its all based on your function that how you can put its structure within a list comprehension or a generator expression,and then apply some changes on it and use python tools based on your needs (in this case we used enumerate).

like image 61
Mazdak Avatar answered Nov 07 '22 23:11

Mazdak