How to find row indices in lists that start with some substring?

I have a list like this:

lines = [ "line", "subline2", "subline4", "line", ] 

And I want to take a list of row indices that starts with some substring.

I use this approach:

 starts = [n for n, l in enumerate(lines) if l.startswith('sub')] 

but maybe someone knows a more beautiful approach?

+6
source share
1 answer

I know that some time has passed since this issue was active, but here is a different solution in any case, if someone is interested.

Your path seems fine, but here is a similar strategy using the list.index() method:

 starts = [lines.index(l) for l in lines if l.startswith('sub')] 

Over time, the two functions work the same way (on average 1.7145156860351563e-06 seconds for your enumerate solution and 1.7133951187133788e-06 seconds for my .index() solution)

+1
source

All Articles