リストがあります:
l=['a','>>','b','>>','d','e','f','g','>>','i','>>','>>','j','k','l','>>','>>']
のすべての隣接要素を抽出し、'>>'
それらをグループに分割する必要があります。これらのグループの間には、要素が存在せず、隣接要素でもありませ'>>'
ん'>>'
。
リストの例では、予想される結果は次のようになります。
[['a', 'b', 'd'], ['g', 'i', 'j'], ['l']]
私はかなりの数のことを試しましたが、単純なものはすべて何らかの形で失敗しました. 現時点で動作していると思われる唯一のコードは次のとおりです。
def func(L,N):
outer=[]
inner=[]
for i,e in enumerate(L):
if e!=N:
try:
if L[i-1]==N or L[i+1]==N:
inner.append(e)
elif len(inner)>0:
outer.append(inner)
inner=[]
except IndexError:
pass
if len(inner):
outer.append(inner)
return outer
func(l,'>>')
Out[196]:
[['a', 'b', 'd'], ['g', 'i', 'j'], ['l']]
うまくいくように見えますが、より良い、よりクリーンな方法があるかどうか疑問に思っていますか?