Reputation: 1377
My goal is to extract from the string below, sub-strings that covers the range of each given indices.
_string='the old school teacher is having a nice time at school'
index_list=[[0,1,2],[4,7,20]]
My attempt:
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 first attempt extracted only the characters that corresponded with the indices, while the second resulted in TypeError
.
Desired output:
['the', 'old school teach']
Any suggestions on how to arrive at the desired output? thanks.
Upvotes: 2
Views: 287
Reputation: 243
_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]
Is it what you are looking for? You only need the first (x[0]) and the last (x[-1]) indexes. Maybe you'll have to change 20 to 21 if you want the whole sentence.
Upvotes: 2
Reputation: 681
You can try in a different approach. First, if I understand correctly your problem, you only need the first and the last index of your list(if it is sorted). So you can try and remove the other values:
second_index = [[x[0],x[-1]] for x in index_list]
and then you can produce your output like that:
[_string[x[0]:x[1]+1] for x in second_index]
Upvotes: 1
Reputation: 9904
If it is just the range that matters, then you can do this:
>>> _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']
So, you should change the index list to [[0,1,2],[4,7,21]]
. And if it is just the first and last item you care about, perhaps you can get rid of the middle element altogether.
Upvotes: 1
Reputation: 27702
If you are delimiting each selection using just the first and last indexes of each selector:
[ _string[x[0]:x[-1]] for x in index_list]
If your last index is inclusive, you should at 1 to the right limit:
[ _string[x[0]:(x[-1]+1)] for x in index_list]
Upvotes: 1