Reputation: 1054
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
Upvotes: 0
Views: 94
Reputation: 36
list_char = ['a','b','c','s','a','d','g','b','e']
index = "".join(list_char).rindex('s')
print list_char[index:]
Upvotes: -1
Reputation: 1396
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')
Upvotes: 0
Reputation: 362557
>>> 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']
Upvotes: 4
Reputation: 34017
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']
Upvotes: 1