gpt4 book ai didi

python - 如何根据索引提取子串

转载 作者:行者123 更新时间:2023-11-28 21:55:45 25 4
gpt4 key购买 nike

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

_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

第一次尝试仅提取与索引对应的字符,而第二次尝试导致 TypeError

期望的输出:

['the', 'old school teach']

关于如何获得所需输出的任何建议?谢谢。

最佳答案

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

是您要找的吗?您只需要第一个 (x[0]) 和最后一个 (x[-1]) 索引。如果您想要整个句子,也许您必须将 20 更改为 21。

关于python - 如何根据索引提取子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22450222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com