[英]How do I get the consecutive elements between two identical elements in a list?
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. 例如,我有一个列表
l = ['.','b','w','w','w','b','.','.']
,我将如何遍历此列表并返回b之间的三个w的索引。
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. 我需要能够处理
l = ['.','b','w','w','w','w','.','.']
,第二个“ b”,在这种情况下,将不会返回任何内容。 Other cases that could be encountered are l = ['.','b','w','w','.','.','b','.']
, in this case nothing would be returned either. 可能遇到的其他情况是
l = ['.','b','w','w','.','.','b','.']
,在这种情况下将不返回任何内容无论是。 I need to be able to get the consecutive w's between the b's. 我需要能够获得b之间的连续w。 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 ?
如果没有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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.