For example I have a list l = ['.','b','w','w','w','b','.','.']
, how would I traverse this list and return the indices of the three w's that are between the b's.
I need to be able to handle cases such as l = ['.','b','w','w','w','w','.','.']
, where there is no second 'b', in this case nothing would be returned. Other cases that could be encountered are l = ['.','b','w','w','.','.','b','.']
, in this case nothing would be returned either. I need to be able to get the consecutive w's between the b's. What I have tried so far is this:
l = ['.','b','w','w','.','.','.','.']
q = []
loop = False
for i in range(len(l)):
if l[i] == 'b' and l[i+1] == 'w':
loop = True
elif l[i] == 'w' and l[i+1] == 'w' and l[i+2] == '.':
pass
elif l[i] == 'w' and l[i-1] == 'b' and l[i+1] == 'w' and loop == True:
q.append(i)
elif l[i-1] == 'w' and l[i] == 'w' and l[i+1] == 'w' and loop == True: q.append(i)
elif l[i] == 'w' and l[i+1] == 'b' and loop == True:
q.append(i)
loop = False
break
print(q)
But this does not handle all cases and sometimes returns errors. How could I go about doing this without numpy ?
try this
import re
l = ['.','b','w','w','b','.','.','.']
s = ''.join(l)
# print(re.findall('[b]([w]+)[b]',s))
# print(re.findall('[w]([b]+)[w]',s))
if(re.findall('[b]([w]+)[b]',s)):
witer =re.finditer('w',s)
wpos = []
for i in witer:
wpos.append(i.start())
print('reverse', wpos)
if(re.findall('[w]([b]+)[w]',s)):
biter =re.finditer('b',s)
bpos = []
for i in biter:
bpos.append(i.start())
print('reverse', bpos)
Try this:
ind = [i for i, e in enumerate(l) if e == 'b']
q = []
if len(ind) == 2:
w = l[ind[0]+1: ind[1]]
if set(w) == {'w'}:
for i in range(ind[0]+1, ind[1]):
q.append(i)
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.