Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表的最后一个元素提取到某个字符串_Python_List Comprehension - Fatal编程技术网

Python 从列表的最后一个元素提取到某个字符串

Python 从列表的最后一个元素提取到某个字符串,python,list-comprehension,Python,List Comprehension,我需要帮助来实现这一点: list_char = ['a','b','c','s','a','d','g','b','e'] 我需要这个输出: ['s','a','d','g','b','e'] 因此,从最后一个元素开始,直到找到第一个“s”(之前我可以有更多的“s”,因此我必须从最后一个元素开始) 可能吗 谢谢将列表转换为字符串,然后再转换回: In [83]: l = ['a','b','c','s','a','d','g','b','e'] In [85]: s=''.join(l)

我需要帮助来实现这一点:

list_char = ['a','b','c','s','a','d','g','b','e']
我需要这个输出:

['s','a','d','g','b','e']
因此,从最后一个元素开始,直到找到第一个“s”(之前我可以有更多的“s”,因此我必须从最后一个元素开始)

可能吗


谢谢

将列表转换为字符串,然后再转换回:

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']

将列表转换为字符串,然后再转换回:

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']

我会用numpy来做这件事,因为它允许简单的操作

list_char = ['a','b','c','s','a','d','g','b','e']
test = np.array(list_char)
这给了我们一个字符串数组,现在我们需要找到数组中最后的s

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

test[ind:]
#prints array(['s', 'a', 'd', 'g', 'b', 'e'], dtype='|S1')

我会用numpy来做这件事,因为它允许简单的操作

list_char = ['a','b','c','s','a','d','g','b','e']
test = np.array(list_char)
这给了我们一个字符串数组,现在我们需要找到数组中最后的s

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

test[ind:]
#prints array(['s', 'a', 'd', 'g', 'b', 'e'], dtype='|S1')

@wnnmaw:nope的可能重复,这是关于从末尾开始的索引搜索,而不是关于切片。您的输入始终是单个字符的列表吗?@wnnmaw:nope的可能重复,这是关于从末尾开始的索引搜索,而不是关于切片。您的输入始终是单个字符的列表吗?谢谢您的建议。“是否可以只使用列表理解符号?”主持人wim提出了这一点,谢谢你的建议。只有使用列表理解符号才能做到吗?@指挥者wim提供了这一点