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

How to get items from a list based on specific item in Python

I have below list

l = ['7E', '00', '10', '97', '9A', '00', '13', 'A2', '00', '41', 'B6', '13', '58', 'FF', 'FE', '41', '50', '00', '01', '28']

From above list, I want to extract 41 B6 13 58, which always comes after 00 13 A2 00 and is always length 4.

I thought of extracting this based on the index of 00 (just before 41) but there can be many 00 in the list so this will not be always correct.

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

So I have to make sure its always 00 13 A2 00 and then get the index of 00 (which is after A2) and from this index extract next 4 items which should be the final output. But I am unable to decide how to go for it. Can anyone please help.

>Solution :

for i in range(0, len(l)-8):
    if l[i:i+4] == ['00', '13', 'A2', '00']:
        return l[i+4:i+8]

So what we are doing: looking linearly for those four given values (indices i, i+1, i+2, and i+3), and if we find them, we take the next four values from the list – indices i+4, i+5, i+6, and i+7.

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