[英]Extract from last element of a list to a certain string
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) 因此,从最后一个元素开始,直到找到第一个“ s”(之前我可以有更多“ s”,所以我必须从最后一个元素开始)
Is it possible? 可能吗?
Thank you 谢谢
>>> 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']
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']
I would do this with numpy, since it allows for easy manipulation. 我将使用numpy进行此操作,因为它允许轻松操作。
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')
list_char = ['a','b','c','s','a','d','g','b','e']
index = "".join(list_char).rindex('s')
print list_char[index:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.