0

I need help to achieve this:

list_char = ['a','b','c','s','a','d','g','b','e']

I need this output:

['s','a','d','g','b','e']

So starting from the last element until the first 's' found (I can have more 's' before, so I have to start from the last element)

Is it possible?

Thank you

The Condor
  • 1,034
  • 4
  • 16
  • 44

4 Answers4

4
>>> list_char = ['a','b','c','s','a','d','g','b','e']
>>> list_char[-list_char[::-1].index('s')-1:]
['s', 'a', 'd', 'g', 'b', 'e']
wim
  • 338,267
  • 99
  • 616
  • 750
1

convert the list to a string and then convert back:

In [83]: l = ['a','b','c','s','a','d','g','b','e']

In [85]: s=''.join(l)

In [87]: list(s[s.rfind('s'):])
Out[87]: ['s', 'a', 'd', 'g', 'b', 'e']
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
0

I would do this with numpy, since it allows for easy manipulation.

list_char = ['a','b','c','s','a','d','g','b','e']
test = np.array(list_char)

This gives us an array of the strings, and now we need to find the last s in the array,

ind = np.where(test=='s')[-1]
#returns 3 in this cause, but would return the last index of s

Then slice

test[ind:]
#prints array(['s', 'a', 'd', 'g', 'b', 'e'], dtype='|S1')
Wesley Bowman
  • 1,366
  • 16
  • 35
-1
list_char = ['a','b','c','s','a','d','g','b','e']
index = "".join(list_char).rindex('s')
print list_char[index:]
coderusher
  • 36
  • 4