Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting strings from list on multiple conditions

I have the following list:

fields = ['angDist','angDist','_RAJ2000','_DEJ2000','NVSS','RAJ2000',
                  'DEJ2000','e_RAJ2000','e_DEJ2000','S1.4','e_S1.4','l_MajAxis',
                  'MajAxis','l_MinAxis','MinAxis','f_resFlux','_RAJ2000',
                  '_DEJ2000','GLEAM','RAJ2000','DEJ2000','Fpwide','Fintwide',
                  'eabsFpct','efitFpct','Fp076','Fint076','Fp084','Fint084',
                  'Fp092','Fint092','Fp099','Fint099','Fp107','Fint107','Fp115',
                  'Fint115','Fp122','Fint122','Fp130','Fint130','Fp143',
                  'Fint143','Fp151','Fint151','Fp158','Fint158','Fp166',
                  'Fint166','Fp174','Fint174','Fp181','Fint181','Fp189',
                  'Fint189','Fp197','Fint197','Fp204','Fint204','Fp212',
                  'Fint212','Fp220','Fint220','Fp227','Fint227','alpha',
                  'Fintfit200','RAdeg','DEdeg','errHalfMaj','errHalfMin',
                  'errPosAng','objID','mode','q_mode','class','SDSS12',
                  'm_SDSS12','flags','ObsDate','Q','umag','e_umag','gmag',
                  'e_gmag','rmag','e_rmag','imag','e_imag','zmag','e_zmag','zsp',
                  'e_zsp','f_zsp','zph','e_zph','avg_zph','pmRA','e_pmRA','pmDE',
                  'e_pmDE','SpObjID','spType','spCl','subClass'
]

and I need to extract a list of the strings starting with Fp or ending with mag, but not starting with e_.

I’ve tried a list comprehension:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    magnames1 = [mag for mag in fields if mag.startswith('Fp')]
    magnames2 = [mag for mag in fields if (mag.endswith('mag') && !(mag.startswith"e_"))]
    magnames = magnames1 + magnames2

but magnames2 gives me a syntax error. What’s the easiest way to do this without hardcoding the strings into another list?

>Solution :

You want and instead of && and not instead of !:

magnames1 = [mag for mag in fields if mag.startswith('Fp')]
magnames2 = [mag for mag in fields if (mag.endswith('mag') and not mag.startswith("e_"))]
magnames = magnames1 + magnames2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading