Python 如何基于索引提取子字符串

Python 如何基于索引提取子字符串,python,string,indices,Python,String,Indices,我的目标是从下面的字符串中提取覆盖每个给定索引范围的子字符串 _string='the old school teacher is having a nice time at school' index_list=[[0,1,2],[4,7,20]] 我的尝试: 1)>>> [[[_string[y] for y in x]for x in index_list] [['t', 'h', 'e'], ['o', ' ', 'e']] 2)>>>[_stri

我的目标是从下面的字符串中提取覆盖每个给定索引范围的子字符串

_string='the old school teacher is having a nice time at school'
index_list=[[0,1,2],[4,7,20]]
我的尝试:

1)>>> [[[_string[y] for y in x]for x in index_list]
[['t', 'h', 'e'], ['o', ' ', 'e']]

2)>>>[_string[x[0:]] for x in index_list]
TypeError: string indices must be integers, not list
第一次尝试只提取与索引相对应的字符,而第二次尝试则导致
类型错误

期望输出:

['the', 'old school teach']

关于如何达到期望的输出有什么建议吗?谢谢。

如果您仅使用每个选择器的第一个和最后一个索引来界定每个选择:

[ _string[x[0]:x[-1]] for x in index_list]
如果您的上一个索引包含在内,则应将其设置为1,以达到正确的限制:

[ _string[x[0]:(x[-1]+1)] for x in index_list]

如果重要的只是范围,那么您可以这样做:

>>> _string='the old school teacher is having a nice time at school'
>>> index_list=[[0,1,2],[4,7,20]]
>>> [_string[i[0]:i[-1]+1] for i in index_list]
['the', 'old school teache']

因此,您应该将索引列表更改为
[[0,1,2],[4,7,21]
。如果它只是你关心的第一个和最后一个项目,也许你可以完全去掉中间的元素。

你可以尝试另一种方法。 首先,如果我正确理解您的问题,您只需要列表的第一个和最后一个索引(如果已排序)。因此,您可以尝试删除其他值:

second_index = [[x[0],x[-1]] for x in index_list]
然后,您可以像这样生成输出:

[_string[x[0]:x[1]+1] for x in second_index]
这就是你要找的吗? 您只需要第一个(x[0])和最后一个(x[-1])索引。
如果你想要完整的句子,也许你必须将20改为21。

你能解释一下你的索引列表的格式吗?在我看来,你的索引列表项的第二个索引是无用的,因为你描述的所需输出似乎仅仅基于每个条目的第一个和最后一个索引。我说的对吗?即使是第一个和最后一个索引,输出也不一致。也许列表中的第二项应该是[4,21]?@PabloFranciscoPérezHidalgo[0:2],而[4:20]没有给出所需的输出。@PabloFranciscoPérezHidalgo,你完全正确。这只是范围问题。@M4rtini我不知道最后一个字符是否包含他,我将编辑我的答案来描述这种情况。
_string='the old school teacher is having a nice time at school'
index_list=[[0,1,2],[4,7,20]]
print [_string[x[0]:x[-1]+1] for x in index_list]