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

Python Lists – Return list of every nth element before known substring in a list

I have an array like so:

['6.00', '1.85', 'X', '2.25', '1.26', 'X', '6.50', '1.80', 'X', '6.50', '1.95', 'X', '34.00', '5.50']

Does anyone know how I could return an array of every 3rd element before ‘X’?:

['6.00', '2.25', '6.50', '6.50']

I have been removing every 2nd and 3rd element by the following code, but it breaks when there are more elements past the last ‘X’ in the list or when the ‘X’ is not evenly spaced:

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

data = ['6.00', '1.85', 'X', '2.25', '1.26', 'X', '6.50', '1.80', 'X', '6.50', '1.95', 'X', '34.00', '5.50']
x = np.array(data)
x = np.delete(x, np.arange(1, x.size, 3))
x = np.delete(x, np.arange(1, x.size, 2))

>Solution :

By using offset of positions (found by np.nonzero) where x == 'X':

x[np.nonzero(x == 'X')[0] - 2]

array(['6.00', '2.25', '6.50', '6.50'], dtype='<U5')
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