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

Time:11-07

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.

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.

CodePudding user response:

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.

CodePudding user response:

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


str_l = " ".join(l)
print(str_l)

position = str_l.find(SEQUENCE)   # this gives us the position where the sequence starts
print(position)

required = "xx xx xx xx"    # assuming we dont know what exactly to extract, but we know its length
req = str_l[position len(SEQUENCE) 1: position   len(SEQUENCE) len(required) 1]
print(req)  

# to get the required output
req = req.split(" ")
print(req)
  • Related