I have an array, lets say this:
arr = ["60", "DD", "81", "01" , "01", "29", "B8", "1B", "00", "30", "2C", "46", "00", "0A", "81", "02" , "0D", "25", "00", "37", "41", "31", "00", "C2", "7F", "06", "00", "17", "94", "1A", "00", "48", "06", "05", "00", "5C", "7F", "3E", "87", "FF", "0F", "B8", "0A", "38", "0C"]
I am trying to replace every occurance of "81", "01"
with "81"
and "81", "02"
with "82"
. I tried but it not replacing the values appropriately. Here is my code.
import numpy as np
values = np.array(arr)
searchval = ["81", "01"]
N = len(searchval)
possibles = np.where(values == searchval[0])[0]
solns = []
for p in possibles:
check = values[p:p+N]
if np.all(check == searchval):
arr.pop(p+1)
solns.append(p)
print(solns)
It would be great if someone can help me solving this. Thank you.
Given your two character strings, you could convert the list to string and do replacements with str.replace
then split to return the transformed list:
s = ' '.join(arr)
s = s.replace('81 01', '81')
s = s.replace('81 02', '82')
print s.split()
# ['60', 'DD', '81', '01', '29', 'B8', '1B', '00', '30', '2C', '46', '00', '0A', '82', '0D', '25', '00', '37', '41', '31', '00', 'C2', '7F', '06', '00', '17', '94', '1A', '00', '48', '06', '05', '00', '5C', '7F', '3E', '87', 'FF', '0F', 'B8', '0A', '38', '0C']
Not very efficient but qiute concise and readable.
For an approach that works just with the list, and would generalize to other kinds of values:
solns = [arr[0]]
for i, entry in enumerate(arr[:-1]):
if entry == '81':
if arr[i+1] == '02':
solns[-1] = '82'
elif not arr[i+1] == '01':
solns.append(arr[i+1])
else:
solns.append(arr[i+1])
Or, if you prefer:
solns = [arr[0]]
for i, entry in enumerate(arr[:-1]):
if entry == '81':
if arr[i+1] == '02':
solns[-1] = '82'
continue
elif arr[i+1] == '01':
continue
solns.append(arr[i+1])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.