How to store indexes in a list

I want to find specific line segments and save them, however I would need to store a large number of these lines, and I thought it would be more elegant to store them as indexes of the main line, and not as a list of lines. I'm having trouble getting indexes to use. For example:

index1 = [0:3, 4:8] #invalid syntax index2 = ['0:3','5:6'] s = 'ABCDEFGHIJKLMN' print(s[index2[0]]) #TypeError string indices must be integers 

Am I thinking about it wrong?

+7
python
source share
2 answers

The colon-based clipping syntax is only valid inside the index operator, for example. x[i:j] . Instead, you can store slice objects in your list, where slice(x,y,z) equivalent to x:y:z , for example.

 index = [slice(0,3), slice(5,6)] print([s[i] for i in index]) 

will print:

 ['ABC', 'F'] 
+14
source share

Your idea of ​​storing indexes instead of real substrings is good.

As for the mechanism, you should save (start, end) the numbers as a tuple of two integers:

 index1 = [(0,3), (4,8)] 

When you need to play a substring, write the code as follows:

 pair = index1[0] # (0,3) sub = s[pair[0] : pair[1]] # 'ABC' 
+4
source share

All Articles