Home > other >  Extracting strings from list on multiple conditions
Extracting strings from list on multiple conditions

Time:12-06

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:

    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?

CodePudding user response:

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

CodePudding user response:

It should work if you use the keyword not instead of ! and a single & instead of &&.

  • Related