jeudi 4 octobre 2018

Python inserting multiple elements in one iteration in list comprehension conditionally

Suppose we have to insert two elements in a list comprehension in one iteration, but we have to choose which two to insert. How do we make such a list comprehension.

For example:- Suppose we have a list hostnames = ['aa', 'bb', 'dd', 'pp', 'bb', 'zz', 'hh'].

Now we want to modify this list such that hostnames starting with p should have an extra element called '_prd' ( eg. 'pp_prd') and similarly an extra element for hostnames starting with h with the value '_uat'.(eg 'hh_uat').

So the desired output for the above list would be mod_hostnames = ['aa', 'bb', 'dd', 'pp_prd', 'pp', 'bb', 'zz', 'hh_uat','hh'].

Now I thought of writing it out like this -

>>> fh=lambda x: x+'_uat'
>>> fp=lambda x:x+'_prd'
>>> fo=lambda x:x
>>> lis
['aa', 'bb', 'dd', 'pp', 'bb', 'zz', 'hh']
>>> hostnames = lis
>>> mod_hostnames = [f(host) for f in (fo,fp) if host[0]=='p' else f(host) for f in (fo,fh) if host[0]=='h' else host for host in hostnames]
  File "<stdin>", line 1
    mod_hostnames = [f(host) for f in (fo,fp) if host[0]=='p' else f(host) for f in (fo,fh) if host[0]=='h' else host for host in hostnames]
                                                                 ^
SyntaxError: invalid syntax

We get a syntax error. I also know that in list comprehensions the second loop runs faster (just like in for loops) and in our code, the host in hostnames is running faster instead of the other desired way round. So I tried this :-

>>> mod_hostnames = [f(host) for host in hostnames for f in (fo,fp) if host[0]=='p' else for f in (fo,fh) if host[0]=='h' else for f in (fo)]  
File "<stdin>", line 1
    mod_hostnames = [f(host) for host in hostnames for f in (fo,fp) if host[0]=='p' else for f in (fo,fh) if host[0]=='h' else for f in (fo)]
                                                                                       ^
SyntaxError: invalid syntax

Any suggestions? Or is this not possible in list comprehensions. I know that this is not readable at all and there are much better ways to write this out. (eg using a dict 'switch' to write this in one statement inside a for loop, or the good old if else in a loop, etc).

Aucun commentaire:

Enregistrer un commentaire