Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store indices in a list

I want to find certain segments of a string and store them, however, I will need to store a large number of these strings and I was thinking that it might be more elegant to store them as indices of the master string rather than as a list of strings. I am having trouble retrieving the indices for 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 this the wrong way?

like image 554
Sam Avatar asked May 06 '15 04:05

Sam


People also ask

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

How do you add an indice to a list in Python?

To add an element to a given Python list, you can use either of the three following methods: Use the list insert method list. insert(index, element) . Use slice assignment lst[index:index] = [element] to overwrite the empty slice with a list of one element.

Is indexing possible in list?

The elements of a list can be accessed by an index. To do that, you name the list, and then inside of a pair of square brackets you use an index number, like what I'm showing right here. 00:17 That allows access to individual elements within the list. The indexing for the list is zero-based.


2 Answers

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

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

will print:

['ABC', 'F']
like image 133
Ray Avatar answered Oct 16 '22 21:10

Ray


Your idea of storing indices instead of actual substrings is a good one.

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

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

When it's time to reproduce the substring, write code like this:

pair = index1[0]  # (0,3)
sub = s[pair[0] : pair[1]]  # 'ABC'
like image 28
Nayuki Avatar answered Oct 16 '22 21:10

Nayuki